reactjs - 如何访问 getDerivedStateFromProps 中的组件函数

标签 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() {}
}

this.updateVariables(); 不工作。如何调用 updateVariables()

最佳答案

this 不能在静态函数内部访问,这是设计使然。不过,如果你想在 getDerivedStateFromProps 中获取 this,你可以使用下面的代码,但你永远不应该这样使用。

constructor() {
  super();
  this.state = {
    currentInstance: this
  }
}

现在在您的 getDerivedStateFromProps() 中访问 currentInstancethis

static getDerivedStateFromProps(props, state) {
   state.currentInstance.updateVariables();
}

关于reactjs - 如何访问 getDerivedStateFromProps 中的组件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52307007/

相关文章:

javascript - 像在 IDE 中一样在文本区域中使用react自动完成(例如 VS Code、Atom)

asp.net - 使用 React 在 ASP.NET Core 应用程序中包含图像

reactjs - 如何将 Bootstrap JS 和 Jquery JS 添加到 Next JS

reactjs - 在 ReactJS 中使用 PropTypes 类型检查 params.id

reactjs - react 键无法添加到元素

reactjs - enzyme /Jest react 测试 - 具有 react-redux > 6 的浅连接组件

javascript - 获取数据的异步 redux 操作导致组件重新加载并导致对重新加载中的最大深度使用react

reactjs - typescript react 组件中的 react / Prop 类型eslint错误

django - 我应该在哪里排序和过滤?后端还是前端?

reactjs - TextInput 清除时速度慢,屏幕上有很多内容