您的位置:首页 > Web前端 > React

ReactJS笔记03--状态

2016-07-15 00:12 369 查看
在说状态之前先了解两个函数

一个是:getInitialState

FB的解释:

Invoked once before the component is mounted. The return value will be used as the initial value of this.state.

翻译过来就是:

在组件挂载之前调用一次。返回值将会作为 this.state 的初始值

第二个函数:setState

FB的解释:

Performs a shallow merge of nextState into current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks.

翻译:

合并 nextState 和当前 state(PS:这里其实就是将下一个状态的值赋值给当前状态)。这是在事件处理函数中和请求回调函数中触发 UI 更新的主要方法。另外,也支持可选的回调函数,该函数在 setState 执行完毕并且组件重新渲染完成之后调用。

**注意:

绝对不要直接改变 this.state,因为在之后调用 setState() 可能会替换掉你做的更改。把 this.state 当做不可变的**

好吧 了解了函数后 咱们来个代码:

var ClcikApp = React.createClass({
getInitialState:function() {
return {
clickCount: 0,
}
},
handleClick:function(){  //注意这里只能通过setstate方法更改this.state的值
this.setState({
clickCount: this.state.clickCount + 1
})
},
render:function(){
return(
<div>
<h2> click </h2>
<button onClick={this.handleClick}>click me</button>
<p> all click count:{this.state.clickCount}</p>
</div>
)
}
})
var clickCom = ReactDOM.render(
<ClcikApp/>,
document.getElementById("content")
)


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: