反应 | TypeScript - "this" onClick 事件的上下文

React | TypeScript - Context of "this" onClick event

在下面的上下文中,分配 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 的任何调用都会退化为其在外部范围内的值。

但是,我找不到解决这个问题的方法(双关语:)

更新: 根据下面的一些评论,我将代码重构为:

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>;
};

修复

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 是一个函数