Parent 告知 children
Parent inform children
我有一个包含很多项目 (children) 的列表 (parent)。列表上有一个巨大的保存按钮。当用户按下该按钮时,我希望触发所有 childrens save()
方法。
通常,我会为此使用自定义事件(或某些 PubSub 实现),但我想知道:React.js 实现此目的的方法是什么?
parent 应具有状态并使用 props 渲染 children。这只是一个示例,未经测试。
Parent:
var Parent = React.createClass({
getInitialState: function(){
return {array: []}
},
handleChange: function(key, value){
// here will you get key and value from child input.
this.setState({array[key]: value});
},
saveAll: function(){
// this.state.array have all data, lets save it :)
},
render: function(){
var self = this;
var items = [];
this.state.array.map(function(item, key){
items.push(<Child handleChange={self.handleChange} index={key} value={item} />);
});
return (<div>{items} <button onClick={this.saveAll}>SaveAll</button> </div>
}
});
Child:
var Child = React.createClass({
onChange: function(event){
this.props.handleChange(this.props.index, event.target.value);
},
render: function(){
return (<li><input value={this.props.value} onChange={this.onChange} />)
}
});
我有一个包含很多项目 (children) 的列表 (parent)。列表上有一个巨大的保存按钮。当用户按下该按钮时,我希望触发所有 childrens save()
方法。
通常,我会为此使用自定义事件(或某些 PubSub 实现),但我想知道:React.js 实现此目的的方法是什么?
parent 应具有状态并使用 props 渲染 children。这只是一个示例,未经测试。
Parent:
var Parent = React.createClass({
getInitialState: function(){
return {array: []}
},
handleChange: function(key, value){
// here will you get key and value from child input.
this.setState({array[key]: value});
},
saveAll: function(){
// this.state.array have all data, lets save it :)
},
render: function(){
var self = this;
var items = [];
this.state.array.map(function(item, key){
items.push(<Child handleChange={self.handleChange} index={key} value={item} />);
});
return (<div>{items} <button onClick={this.saveAll}>SaveAll</button> </div>
}
});
Child:
var Child = React.createClass({
onChange: function(event){
this.props.handleChange(this.props.index, event.target.value);
},
render: function(){
return (<li><input value={this.props.value} onChange={this.onChange} />)
}
});