【发布时间】: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一起使用 -
是的,你知道我该如何妥善解决这个问题吗?
-
使用普通函数:
() => {tofunction() { -
要解决在不应该使用箭头函数的情况下使用箭头函数的问题,只需不使用箭头函数即可。您可以使用
= function() { ... };定义一个函数 -
你的意思是
function append() { ... }吗?它错误:Cannot read property 'append' of undefined和TS错误this保持不变
标签: javascript reactjs typescript ecmascript-6 tslint