React中props與state的區別

首先,props與state是React組件的兩種方法。

  1. props,可以在組件中來獲取this.props的屬性。

var Helloreact=React.createClass({
    render:function(){
        return <h1>Hello {this.props.name}</h1>
        }
});
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 <h1>Hello {this.state.name}</h1>
        }
});
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}/>
                            <h1>Hi {this.props.value} {value}</h1>
                            <button onClick={this.clickhandle}>清除{value}</button>
                            </div>;
                }
            });
            ReactDOM.render(
                <div style={myStyle}><HelloMe/></div>,
                document.getElementById('example1')
            );

所以言之,相對於靜態的狀態下使用props會更好一些,動態的數據就需要使用state,

而React中,是虛擬的DOM樹,是遍歷全局後對數據進行對比,然後運算使用最快的方法進行的渲染。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章