假设我有一个Parent组件和一个子组件,它们都具有共同'item'值的状态。
如何在Parent和Child状态中同步'item'值?
更具体地说,父母可以是应用程序的页面,孩子可以是个人化的输入。当我在输入中写入时,我希望更新页面状态,并且当页面状态由外部因素(例如通知)更新时,我希望更新输入。
export default class Parent extends Component {
constructor(props) {
super(props);
this.state={
item: 1,
}
}
render() {
return (
<Child
item = this.state.item
/>
)
}
// I want any function of this type to automatically update
// child state (and redraw child) without having to manually resynchronise
modifyItem() {
this.setState({ item: neValue })
}
}
export default class Child extends Component {
constructor(props) {
super(props);
this.state={
item: this.props.item,
}
}
// I want any function of this type to automatically update
// parent state without having to manually resynchronise
modifyItem() {
this.setState({ item: neValue })
}
}
答案 0 :(得分:0)
export default class Parent extends Component {
constructor(props) {
super(props);
this.state={
item: 1,
}
}
onItemChange(item) {
this.setState({ item });
}
render() {
return (
<Child
item = this.state.item
onItemChange={this.onItemChange.bind(this)}
/>
)
}
// I want any function of this type to automatically update
// child state (and redraw child) without having to manually resynchronise
modifyItem() {
this.setState({ item: neValue })
}
}
export default class Child extends Component {
constructor(props) {
super(props);
this.state={
item: this.props.item,
}
}
// I want any function of this type to automatically update
// parent state without having to manually resynchronise
modifyItem() {
this.setState({ item: newValue })
if (this.props.onItemChange) {
this.props.onItemChange(newValue);
}
}
}