我定义了一个类来在React登录页面上呈现身份验证方法,该接口包括一个我想覆盖的默认呈现函数。
class AuthMethod {
constructor(initializer: Pick<AuthMethod, 'id'> & Partial<AuthMethod>) {
Object.assign(this, initializer);
}
id!: string;
text: string = "";
enabled: boolean = false;
icon: React.ReactNode = React.Fragment;
render: () => React.ReactNode = () => (
<WhiteIconButton key={this.id} disabled={!this.enabled} >
{this.icon}
</WhiteIconButton>
);
}
我初始化了这些数组,以便在一些地方使用(例如登录表单):
const authMethods: AuthMethod[] = [
new AuthMethod({
id: "auth_facebook",
text: "Sign in with Facebook",
enabled: false,
icon: <FontAwesomeIcon icon={faFacebookSquare} />,
// render: () => this.icon // This doesn't work
}),
new AuthMethod({
id: "auth_twitter",
text: "Sign in with Twitter",
enabled: false,
icon: <FontAwesomeIcon icon={faTwitter} />
}),
new AuthMethod({
id: "auth_google",
text: "Sign in with Google",
enabled: true,
icon: <FontAwesomeIcon icon={faGoogle} />
})
];
以后我可以像这样渲染它们:
<div className={classes.socialLine}>
{ authMethods.map(m => m.render()) }
</div>
问题是我无法使用使用类的属性的箭头来覆盖“ render”箭头,在Facebook示例中,如果我取消注释“ render:”行,则会收到错误消息“包含的箭头函数捕获全局值”这个的'”。
如何访问提供的箭头功能中的成员属性?
编辑:您可以在这里运行它:https : //codesandbox.io/s/tender-bhabha-8jdmf?fontsize=14&hidenavigation=1&theme=dark
只需取消注释“ render:”行即可查看问题。
解:
感谢jcalz提供了答案,箭头函数无法访问“ this”属性(因为它绑定到创建该属性的任何“ this”)。因此解决方案是使用“正常”功能(非箭头)。我以为当类定义中的签名是箭头函数时,这是行不通的,但事实并非如此,解决方案是:
new AuthMethod({
id: "auth_facebook",
text: "Sign in with Facebook",
enabled: false,
icon: <FontAwesomeIcon icon={faFacebookSquare} />,
render: function() {
return this.icon;
}
}),
您可以在这里查看它的运行情况:https : //8jdmf.csb.app/
箭头函数没有自己的this
上下文,这与非箭头函数(例如,用function
关键字定义的函数)不同。因此,this
在箭头函数主体中进行的任何提及实际上都this
将引用其词法上下文中所指的内容,这不是您想要的。
这里最直接的解决方案是放弃箭头功能。您可以使用类似的匿名函数function(){return this.icon}
,也可以使用terser方法语法:
new AuthMethod({
render(){return this.icon},
id: "auth_facebook",
text: "Sign in with Facebook",
enabled: false,
icon: <FontAwesomeIcon icon={faFacebookSquare} />
}),
这应该可行,并且可以说是您正在做的事情的常规方式。好吧,希望能有所帮助;祝好运!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句