最佳答案
这可能在可回答性和固执己见之间徘徊,但是我将反复讨论如何随着复杂性的增长构建 ReactJS 组件,并且可以使用一些方向。
来自 AngularJS,我想将我的模型作为一个属性传递给组件,并让组件直接修改模型。或者我应该将模型分解成各种 state
属性,并在发送回上游时将其重新编译在一起?ReactJS 的方法是什么?
Take the example of a blog post editor. Trying to modify the model directly ends up looking like:
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()
,但随着模型的增长,(一篇文章可能有作者、主题、标签、评论、评分等等..。.)组件开始变得非常复杂。
用 ReactLink的第一种方法是否可行?