如何在静态 getDerivedStateFromProps 中调用组件函数?
这是我的代码
class Box extends Component {
updateVariables() {
this.statColorClass = "no-change";
if(this.props.dir === "up") {
this.statColorClass = "up";
this.dirIcon = <GoArrowUp />;
} else if (this.props.dir === "down") {
this.statColorClass = "down";
this.dirIcon = <GoArrowDown />;
}
}
static getDerivedStateFromProps() {
this.updateVariables(); // not working
}
render() {}
}
行 this.updateVariables();
不工作。如何调用 updateVariables()
?
最佳答案
this
不能在静态函数内部访问,这是设计使然。不过,如果你想在 getDerivedStateFromProps 中获取 this
,你可以使用下面的代码,但你永远不应该这样使用。
constructor() {
super();
this.state = {
currentInstance: this
}
}
现在在您的 getDerivedStateFromProps()
中访问 currentInstance
与 this
static getDerivedStateFromProps(props, state) {
state.currentInstance.updateVariables();
}
关于reactjs - 如何访问 getDerivedStateFromProps 中的组件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307007/