温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React中props与state的区别

发布时间:2020-08-04 23:01:45 来源:网络 阅读:6260 作者:shiqidelvtu 栏目:开发技术

首先,props与state是React组件的两种方法。

  1. props,可以在组件中来获取this.props的属性。

var Helloreact=React.createClass({
    render:function(){
        return <h2>Hello {this.props.name}</h2>
        }
});
ReactDOM.render(
    <Helloreact name="BOOM" />,
        document.getElementById('example2')
);      //Hello BOOM

2.state,获取的是更新后的数据,是通过用户的状态来更改state。

var Helloreact=React.createClass({
    getInitialState : function(){
        return {name:'BOOM'};
        },
    render:function(){
        return <h2>Hello {this.state.name}</h2>
        }
});
ReactDOM.render(
    <Helloreact/>,
        document.getElementById('example2')
);    //Hello BOOM

3.在这里,可以通过props获取组件的属性,然后用state动态的更新。

 var HelloMe = React.createClass({
                getDefaultProps:function(){
                    return{
                        value:'props'
                    };
                },
                getInitialState : function(){
                    return {value:'state'};
                },
                handleChange:function(event){
                    this.setState({value:event.target.value});
                },
                clickhandle:function(event){
                    this.setState({value:" "});
                },
                render:function(){
                    var value= this.state.value;
                    return  <div>
                            <input type="text" value={value} onChange={this.handleChange}/>
                            <h2>Hi {this.props.value} {value}</h2>
                            <button onClick={this.clickhandle}>清除{value}</button>
                            </div>;
                }
            });
            ReactDOM.render(
                <div style={myStyle}><HelloMe/></div>,
                document.getElementById('example1')
            );

所以言之,相对于静态的状态下使用props会更好一些,动态的数据就需要使用state,

而React中,是虚拟的DOM树,是遍历全局后对数据进行对比,然后运算使用最快的方法进行的渲染。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI