这可能是在回答问题和固执己见之间徘徊,但我会反复讨论如何随着复杂性的增长构建ReactJS组件,并可能会用到一些方向.
Coming from AngularJS, I want to pass my model into the component as a property and have the component modify the model directly. Or should I be splitting the model up into various 100 properties and compiling it back together when sending back upstream? What is the ReactJS way?
以博客帖子编辑为例.试图直接修改模型的结果如下:
var PostEditor = React.createClass({
updateText: function(e) {
var text = e.target.value;
this.props.post.text = text;
this.forceUpdate();
},
render: function() {
return (
<input value={this.props.post.text} onChange={this.updateText}/>
<button onClick={this.props.post.save}/>Save</button>
);
}
});
这似乎是错的.
让我们的text
模型属性state
,并在保存之前将其编译回模型,这更像是一种react 方式吗
var PostEditor = React.createClass({
getInitialState: function() {
return {
text: ""
};
},
componentWillMount: function() {
this.setState({
text: this.props.post.text
});
},
updateText: function(e) {
this.setState({
text: e.target.value
});
},
savePost: function() {
this.props.post.text = this.state.text;
this.props.post.save();
},
render: function() {
return (
<input value={this.state.text} onChange={this.updateText}/>
<button onClick={this.savePost}/>Save</button>
);
}
});
这不需要调用this.forceUpdate()
,但随着模型的增长,(一篇帖子可能有作者、主题、标签、 comments 、评分等…)组件开始变得非常复杂.
第一种方法是ReactLink吗?