• Props VS State


    Props VS State

    • Props是组件对外的接口,组件树中父级组件向子级组件传递数据和方法的方式,readonly;目的是让外部对组件自己进行配置。
    • State是组件对内的接口,组件内部管理数据的方式,可变,setState会导致组件的重新渲染;目的是让组件控制自己的状态。

    如何分辨何时该用props?何时该用state?

    • 变量需要从父组件中获取,props。
    • 变量在组件的整个生命周期中保持不变,props。
    • 多个组件实现数据共享,props。
    • 组件的事件处理器改变并触发用户界面更新的数据,state。

    Example:


    var HelloMessage = React.createClass({
        render: function () {
            return <h1>Hello {this.props.name}</h1>;
        }
    });
    var App = React.createClass({
        render: function () {
            return <HelloMessage name="W3CSchool" />;
        }
    });
    ReactDOM.render(<App />, document.getElementById('example'));
    //从父组件中获取并且整个生命周期内保持不变,使用props,典型的this.props.children

    //数据共享,使用props
    <A>
        <B1 {...props}></B1>
        <B2 {...props}></B2>
    </A>

    var LikeButton = React.createClass({
        getInitialState: function () {
            return { liked: false };
        },
        handleClick: function (event) {
            //通过事件处理器改变并触发用户界面更新,使用state
            this.setState({ liked: !this.state.liked });
        },
        render: function () {
            var text = this.state.liked ? '喜欢' : '不喜欢';
            return (
                <p onClick={this.handleClick}>
                    你<b>{text}</b>我。点我切换状态。
                </p>
            );
        }
    });

    React.render(
        <LikeButton />,
        document.getElementById('example')
    );
  • 相关阅读:
    赫夫曼树编码
    根据先序和中序实现后序
    C++语言实现开心消消乐
    C语言风格实现的开心消消乐
    动态规划
    leetcode dp wordbreakII
    欧拉回路
    欧拉通路是否存在
    Python|多任务:线程、进程、协程--你想要的都在这里
    网络通信:socket、udp与tcp
  • 原文地址:https://www.cnblogs.com/zouyanzhi/p/12753219.html
Copyright © 2020-2023  润新知