如何在静态 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() {}
}
Run Code Online (Sandbox Code Playgroud)
线路this.updateVariables();不工作。我怎么打电话updateVariables()?
this不能在静态函数内部访问,这是设计使然。如果你想this进入 getDerivedStateFromProps,你可以使用下面的代码,但你永远不应该像这样使用。
constructor() {
super();
this.state = {
currentInstance: this
}
}
Run Code Online (Sandbox Code Playgroud)
现在在您的getDerivedStateFromProps()访问中currentInstance,这与this
static getDerivedStateFromProps(props, state) {
state.currentInstance.updateVariables();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2900 次 |
| 最近记录: |