【问题标题】:React | TypeScript - Context of "this" onClick event反应 | TypeScript - “this” onClick 事件的上下文
【发布时间】:2019-06-10 00:00:20
【问题描述】:

在下面的上下文中,分配this 的正确方法是什么

以下反应功能组件调用并相应地执行我的append() 方法。

export const Guess: React.SFC<{}> = () => {
  const hero = "Spider";
  const animal = "Spider";

  function append() {
    return hero === animal ? "yes" : "no";
  };
  return <p>Are they similar? {append()}</p>;
};

但是,当尝试调用方法onClick,并将函数修改为:

export const Guess: React.SFC<{}> = () => {
  const hero = "Spider";
  const animal = "Spider";

  const append = () => () => {
    return hero === animal ? "yes" : "no";
  };

  return <p onClick={this.append()}>Are they similar? </p>;
};

我收到一个 TS 错误: The containing arrow function captures the global value of 'this' which implicitly has type 'any'

我读到箭头函数没有词法上下文,因此在箭头主体内对this 的任何调用都会退化为其在外部范围内的值。

但是,我无法找到解决方案(双关语:)

更新:基于下面的一些 cmets,我将代码重构为:

export const Guess: React.SFC<{}> = () => {
  const hero = "Spider";
  const animal = "Spider";

  function append() {
    console.log(hero === animal);
    return hero === animal ? 'yes' : 'no';
  }

  return <p onClick={append}>Are they similar? </p>;
};

【问题讨论】:

  • 箭头函数改变this值,你应该避免它与react一起使用
  • 是的,你知道我该如何妥善解决这个问题吗?
  • 使用普通函数:() =&gt; { to function() {
  • 要解决在不应该使用箭头函数的情况下使用箭头函数的问题,只需不使用箭头函数即可。您可以使用= function() { ... }; 定义一个函数
  • 你的意思是function append() { ... } 吗?它错误:Cannot read property 'append' of undefinedTS 错误 this 保持不变

标签: javascript reactjs typescript ecmascript-6 tslint


【解决方案1】:

修复

export const Guess: React.SFC<{}> = () => {
  const hero = "Spider";
  const animal = "Spider";

  const append = () => () => {
    return hero === animal ? "yes" : "no";
  };

  return <p onClick={this.append()}>Are they similar? </p>;
};

应该是:

export const Guess: React.SFC<{}> = () => {
  const hero = "Spider";
  const animal = "Spider";

  const append = () => () => {
    return hero === animal ? "yes" : "no";
  };

  return <p onClick={append}>Are they similar? </p>;
};

更多

简化:this 用于类。你有一个功能。您不需要使用this,因为您没有实例。

onClick 也有一个函数。表达式append() 不是函数。表达式append 是一个函数

【讨论】:

  • 感谢您发布答案和解释,我们是否在建议的重构中缺少( )?我也应用了您建议的更改,但点击时没有触发:请在此处查看沙箱codesandbox.io/s/lpz83843o7跨度>
  • 这是因为thislexically bound
  • @ErikPhilips 你能发表一个答案吗?
  • @basarat 按照您的建议进行操作,点击事件后没有任何反应。
猜你喜欢
  • 2015-03-31
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
相关资源
最近更新 更多