javascript - 反应 | 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>;
};
解决方案
使固定
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
是一个函数。
推荐阅读
- authorization - Swagger 令牌授权
- powershell - PowerShell 字符串中字母的第一个索引
- javascript - 根据对象内部的键对对象进行排序
- java - Java:数据库连接代码问题
- c++ - Qt MacOs 应用程序在退出时使用 dyld::fastBlindLazySymbol 和 sold_stub_binder 崩溃
- c++ - 从给定的二维点计算 SIFT 描述符
- python - 如何评估字典键是否在字符串中
- c - getchar() 时输入回车键;被执行
- json - 如何解码并格式化标记的 LocalDateTime 值
- vue.js - v-dialog 上的内容类不显示自己的样式