gpt4 book ai didi

reactjs - 将代码从使用 .bind(this) 转换为箭头函数

转载 作者:行者123 更新时间:2023-12-03 14:04:16 25 4
gpt4 key购买 nike

我最近被告知在渲染函数中使用bind(this)不好,因为它每次都会创建全新的函数。因此,我正在转向使用箭头函数,如下所示两个 <button>元素。

我的问题是关于 map 功能的。它还使用 .bind(this)。有没有办法将其转换为 ES6/7 格式?

return (
<div>
<button onClick={()=>this.changeDisplayType("images")}>Images</button>
<button onClick={()=>this.changeDisplayType("audio")}>Audio</button>
{
resources.map(function(resource) {
return (
<div key={resource.id}>
<div style={{fontWeight: "bold"}}>{resource.name}</div>
<div>({resource.info})</div>
</div>
)
}.bind(this))
}


</div>
)

我还刚刚意识到我可以完全删除 .bind(this) 并且我的代码仍然有效。因此我也想知道它是否存在有什么区别。

最佳答案

Is there a way to convert this to an ES6/7 format?

是的,你可以这样写,使用arrow function :

resources.map(resource => {
return (
<div key={resource.id}>
<div style={{fontWeight: "bold"}}>{resource.name}</div>
<div>({resource.info})</div>
</div>
)
})

I can remove the .bind(this) completely and my code still works WHY?

因为您没有在 map 正文中使用 this 关键字,这意味着如果您尝试在不绑定(bind)回调方法的情况下访问任何类属性或方法,将会抛出错误。

试试这个:删除绑定(bind)并尝试访问 map 主体内的状态值,它会抛出错误。

关于reactjs - 将代码从使用 .bind(this) 转换为箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45125735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com