【发布时间】:2019-12-17 23:45:09
【问题描述】:
您好,我想将数据从同一个子组件多次传递给父组件。
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
stateVariabes:null
};
// callback from parent
this.props.onSelect(this.state);
}
handleChange(event) {
const value = event.target.value;
this.setState(
{
stateVariabes: value
},
function() {
console.log(this.state);
// callback from parent
this.props.onSelect(this.state);
}
);
}
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
childOne: null,
childList: [],
childOther: null
};
}
childCallbackFunction = childData => {
// which child state shall I set here
this.setState({ weekDay: childData });
};
render() {
return (
<div className="App">
<ChildComponent onSelect={this.childCallbackFunction} />
<ChildComponent onSelect={this.childCallbackFunction} />
<ChildComponent onSelect={this.childCallbackFunction} />
<ChildComponent onSelect={this.childCallbackFunction} />
</div>
);
}
}
当我只使用一个 ChildComponent 时,从子级到父级的状态更新按预期工作,但是当我有 多个 ChildComponent em> 在 Parent 的渲染中不会发生状态更新。
有人可以建议完成任务的正确方法吗?
【问题讨论】:
-
如果我理解得很好,你想在孩子之间分享父状态,好吗?如果是这样,您可以使用渲染道具或子作为功能模式。或者,创建一个上下文。让我知道这是否是您正在寻找的东西
-
嗨,你能做一个可重现的例子here吗?很难说哪里出了问题——你的 ChildComponents 永远不会在你当前的 sn-p 中调用
handleChange -
你能不能试着把你的父母换成 PureComponent 看看它是否有效?
class ParentComponent extends React.PureComponent -
为 childOne、childList 和 childOther 定义单独的 childCallbackFunction 帮助我解决了问题。
标签: javascript html reactjs