首页 > 解决方案 > 反应 | TypeScript - “this” onClick 事件的上下文

问题描述

在下面的上下文中,分配的正确方法是什么 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>;
};

标签: javascriptreactjstypescriptecmascript-6tslint

解决方案


使固定

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


推荐阅读