我需要将一个值index
从父级传递给子级。父级和子级都需要有修改index
的功能。当父进程修改index
时,子进程无法获取更新。有什么我可以解决的吗?
父类:
constructor(props) {
super(props);
this.state = {
index: 0
}
}
parentFunction(dir) {
this.setState({
index: 10
});
}
render() {
return(
<Child index={this.state.index}/>
);}
子类:
constructor(props) {
super(props);
this.state = {
index: this.props.index
};
}
childFunction(dir) {
this.setState({
index: this.props.index+1
});
}
render() {
return(
<div>{this.state.index}</div>
);}
最佳答案
您不需要在两个类中都保留更新程序函数。您可以将更新程序函数从父级传递给子级,并让父级处理状态更新。另外,根据构造函数中的 props 设置状态也是一种反模式。您应该直接将 child 中的 prop 用于您的用例。如果您需要从 props 更新子状态,请确保也在 componentWillReceiveProps
中执行此操作,因为 constructor
仅在第一次调用,并且 每次父级重新渲染时的 componentWillReceiveProps
componentWillReceiveProps(newProps) {
if (newProps.index!== this.props.index) {
this.setState({
index:newProps.index
})
}
}
但是你需要的是
父类:
constructor(props) {
super(props);
this.state = {
index: 0
}
}
parentFunction(dir) {
this.setState({
index: 10
});
}
updaterFunction(dir) {
this.setState((prevState) => ({
index: prevState.index+1
}));
}
render() {
return(
<Child updaterFunction={(val) => this.updaterFunction(val)} index={this.state.index}/>
);}
子类:
updateProps = () => {
this.props.updaterFunction();
}
render() {
return(
<div>{this.props.index}</div>
);}
关于javascript - react : pass value from parent to child does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47049362/