React Props与State

Props

  • properties 使用它把数据传给组件
  • 在挂载组件时设置
  • 只能实例上调用setProps,不许this.setProps
  • 使用this.props访问
1
2
3
4
5
6
7
验证props
propTypes: {
style: View.propTypes.style.isRequired,
elementStyle: View.propTypes.style,
}
//isRequired 可选

State

  • 组件状态
  • this.state 是组件私有的,可以通过调用 this.setState() 来改变它。当状态更新之后,组件重新渲染自己。动态更新的关键点是调用this.setState(),replaceState()使用新对象,替换所有内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var CommentBox = React.createClass({
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
});