如何访问 getDerivedStateFromProps 中的组件函数

pha*_*der 2 reactjs

如何在静态 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()

kir*_*nvj 5

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)