ReactJS State

来源:互联网 发布:域名注册成功后怎么办 编辑:程序博客网 时间:2024/05/09 16:20

我们通过使用getInitialState方法定义组件的初始state属性。

/*** @jsx React.DOM */var APP = React.createClass({    getInitialState: function() {        return {            txt: 'this is some text from initial state'        }    },    render: function(){        return (            <div>              <h1>Hello React</h1>              <p>{this.state.txt}</p>            </div>        )    }});React.renderComponent(<APP />, document.body)

在组件完成加载之后,我们可以通过setState方法来改变我们设置的属性的值。
首先在render函数中加入一个input元素,用于触发onChange事件,然后调用setState方法来设置状态。

/*** @jsx React.DOM */var APP = React.createClass({    getInitialState: function() {        return {            txt: 'this is some text from initial state'        }    },    updateTxt: function(e) {        this.setState({txt: e.target.value})    },    render: function(){        return (            <div>              <input type="text" onChange={this.updateTxt} />              <p>{this.state.txt}</p>            </div>        )    }});



运行以上代码后,当我们在文本框中输入任意文本后,就会触发绑定的onChange事件,之后调用我们定义好的updateTxt方法,从而最终通过setState方法来更新state的数据。

使用replaceState()也是可以替换state的值的.


/** * @jsx React.DOM */  var InterfaceComponent = React.createClass({  getInitialState : function() {    return {      first : "chris",      last  : "pitt"    };  },  handleClick : function() {    this.replaceState({      first : "bob"    });  },  render : function() {    return <div onClick={this.handleClick}>      hello { this.state.first + " " + this.state.last }    </div>;  }});


当你想要清除一些已经在state里面存在的值并且追加一些新值的时候可以使用replaceState()。

当你使用state的时候, 你承担着组件的渲染和行为会出现错误的风险,因此要尽量减少使用state,并且不要在静态的组件上使用state,如果你的组件基于外部因素不需要改变那么就不要使用state,在render()里面计算渲染的值更好。


0 0