【问题标题】:React: Accessing Context in a ES6 Class [duplicate]React:在 ES6 类中访问上下文 [重复]
【发布时间】:2016-03-30 21:48:22
【问题描述】:

使用 ES6 类语法,我无法在类内的其他方法中保留 context 的值。例如:

class Repos extends React.Component {
  constructor(props, context) { // eslint-disable-line
    super(props, context);
    console.log(this.context.router);
  }

  handleSubmit(event) {
    event.preventDefault();
    const userName = event.target.elements[0].value;
    const repo = event.target.elements[1].value;
    const path = `/repos/${userName}/${repo}`;
    console.log(path); // eslint-disable-line
    this.context.router.push(path);
  }

对于第一个控制台日志,上下文仍然存在:

对于第二个控制台日志,没那么多:

如何在构造函数之外的方法中处理this.context,但在类内部?

【问题讨论】:

  • 你怎么称呼handleSubmit

标签: javascript reactjs ecmascript-6


【解决方案1】:

你没有忘记保存上下文的绑定函数吗?

如果您将函数传递给某个操作属性(例如 onSubmit),您应该使用绑定。 React ES6-classes 不会自动绑定方法。

【讨论】:

  • 或使用词法绑定this的箭头函数
猜你喜欢
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 2020-04-08
相关资源
最近更新 更多