我希望能够根据最后一个事件从父级和自身更新子组件属性。
例如:
class MyParent extends Component {
state ={
text:"";
}
render() {
return (
<View>
<MyChild text={this.state.text} />
<Button
onPress={()=>this.setState({text:"parent"})}
title="Update From Parent"
/>
</View>
);
}
}
class MyChild extends Component {
state ={
text:"";
}
componentWillReceiveProps(nextProps) {
if (nextProps.text!== this.state.text) {
this.setState({text:nextProps.text});
}
}
render() {
return (
<View>
{/* I want that the text field will be updated from the last event*/}
<Text>{this.state.text}</Text>
<Button
onPress={()=>this.setState({text:"child"})}
title="Update From Child"
/>
</View>
);
}
}
问题是每次调用setState时都会触发componentWillReceiveProps,因此text属性从父项而不是从子项中获取值。
我怎样才能获得这个结果?
非常感谢 ELAD
答案 0 :(得分:1)
管理您的state
到parent
组件以及pass
将更新state
组件中parent
组件的child
的功能
class MyParent extends Component {
constructor(props) {
super(props);
this.state = {
text: "",
updateParentState: (newState) => this.setState(newState)
}
}
render() {
let { text, updateParentState } = this.state;
return (
<View>
<MyChild data={{ text, updateParentState }} />
<Button
onPress={() => updateParentState({ text: "parent" })}
title="Update From Parent"
/>
</View>
);
}
}
class MyChild extends Component {
constructor(props) {
super(props);
this.state = {
text: props.data.text
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.text !== this.state.text) {
this.setState({ text: nextProps.data.text });
}
}
render() {
let { updateParentState } = this.props.data;
return (
<View>
<Text>{this.state.text}</Text>
<Button
onPress={() => updateParentState({ text: "child" })}
title="Update From Child"
/>
</View>
);
}
}
答案 1 :(得分:0)
你错过了这个。在child中调用setState。请检查这不是问题。
data ChoiceFoo
= FooA
| FooB
data ChoiceBar
= BarB
| BarC
应该是
<Button
onPress={()=>setState({text:"child"})}
title="Update From Child"
/>