【问题标题】:React Table - access state values inside Cell functionsReact Table - 访问 Cell 函数中的状态值
【发布时间】:2020-05-04 14:20:57
【问题描述】:

我有多个使用 Cell 函数的 React-Table 列:

在主类中:

Cell: function (props) {
  return (
    <span>
      <ChildClass
        id={props.original._id} myemail={this.state.email}
      />
    </span>
  );
},

所以我得到了错误:TypeError: Cannot read property 'state' of undefined

我想使用 Cell 函数中的状态。

谢谢

【问题讨论】:

  • 你不能在功能组件中使用this.state
  • 你可以在功能组件内部使用useState钩子来管理状态。 reactjs.org/docs/hooks-state.html
  • 我的案例有什么例子吗?
  • 你能把文件的全部代码贴出来吗?

标签: javascript reactjs function state react-table


【解决方案1】:

函数没有得到"this",你必须将this设为lambda(arrow)函数或需要绑定this。

Cell:(props) => {
  return (
    <span>
      <ChildClass
        id={props.original._id} myemail={this.state.email}
      />
    </span>
  );
},

我希望这对您有用,或者以其他方式分享代码的更多详细信息。

【讨论】:

  • 解决了!你能解释一下为什么吗?
  • 其实在你使用es5的时候,这种情况下,我们必须明确定义“this”,在哪个上下文中使用bind来调用函数,否则,它会占用这是我们定义函数的上下文。但是当我们使用 es6 箭头函数时,它会自动将“this”与我们调用它的函数绑定,因为它没有自己的上下文
猜你喜欢
  • 2016-01-02
  • 2017-07-11
  • 2021-05-04
  • 2022-08-23
  • 2019-12-02
  • 2020-11-20
  • 2019-08-03
  • 2020-10-26
  • 2022-01-01
相关资源
最近更新 更多