刚从React开始,试图替换一个功能性的、尽管非常复杂的jQuery页面。我之所以承担这项任务,是因为我需要添加额外的功能,而继续使用jQuery的复杂网络将变得无法维持。
该页面是一个排序表单,包含多个目的地和与目的地相关的任务。我读到的关于React的所有内容都告诉我要将状态保持在最高的包含级别,本质上是我的OrderCreation/App级别,对吧?
因此,现在我有了一个DestinationInput组件,它通过一个mixin处理GoogleAutocomplete,并具有可切换的编辑状态(在选择了一个自动完成位置后,它变成了一对h4/h6节点-单击它将切换回输入字段)。
我在同一个应用程序中有几个这样的DestinationInput组件——我不希望每个DestinationOutput组件实例有1个destinationUpdated回调——尤其是因为这将成为超时实例的动态数量。
我认为正确的方法是将一个通用回调方法prop传递给子级,并让子级将一个标识符和新值传递给父级。我用钥匙吗?参考文献?我真的没有看到任何关于如何处理多个子实例更新父状态的最佳实践。
我的想法应该工作
var OrderCreate = React.createClass({
getIntitialState = function () {
return {
destinations: []
}
},
updateDestination = function(id, place) {
this.setState(destinations[id], place);
},
render = function() {
return (
for (var i=0; i < this.state.destinations.length; i++) {
<DestinationInput key={ i }
place={this.state.destinations[i]}
onChange={this.updateLocation} />
};
);
}
});
var DestinationInput = React.createClass({
mixins = [GoogleAutocompleteMixin],
getIntitialState = function () {
return {
text: this.props.text
};
},
getDefaultProps = function() {
return {
text: ""
};
},
handleChange = function(event) {
this.setState({text: event.target.value });
},
placeSelected = function(place) {
this.props.onChange(this.props.key, place);
},
render = function() {
return (
<input onChange={ this.handleChange } value={ this.state.text } />
);
}
});
Flux是一种用于在内存中实现数据存储的客户端方法,因此它对服务器上发生的任何事情都是完全不可知的。
我不确定你到底在追求什么,但我想你只是在问把函数传递给孩子们是否是个好主意。是的,非常好。
为了简洁起见,我尝试只包含重要的函数传递内容
class Button extends React.Component {
onClick() {
this.props.onClick( this.props.id )
}
render() {
return <Button onClick={ this.onClick.bind( this ) }>Click me</button>
}
}
class Parent extends React.Component {
onDoStuff( stuff ) {
console.log( stuff ) // comes from each button
}
render() {
return (
<div>
<Button id="number1" onClick={ this.onDoStuff } />
<Button id="number2" onClick={ this.onDoStuff } />
</div>
}
}
}
Parent.onDoStuff
被传递给Button
组件,在那里一个处理程序最终将被附加到DOM节点,DOM节点将解析为调用onDoStuff
(this.props.onClick
)并将相关数据传递回父组件。从那里你可以决定你需要做什么。