gpt4 book ai didi

javascript - 在 React 中,是否有比从映射中引用外部类更标准的方法?

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:39 24 4
gpt4 key购买 nike

对于这个标题的措辞如此糟糕,我感到非常抱歉,但我刚刚学习 React,我得到了一些东西,感觉有点像黑客的方式,我正在尝试正确地弄清楚它。

这是我最初无法运行的代码(removeItem 部分抛出错误,因为 this.removeItem 未定义)。

render() {
return (
<div className="App">
<AddItem addItem={this.addItem.bind(this)} />
<ul>
{this.state.listItems.map(function(item,index){
return (
<ListItem id={index} key={index} title={item} removeItem={this.removeItem.bind(this)} />
);
})}
</ul>
</div>
);
}

我意识到这与范围有关,因为 map() 内的“this”并不是指与 addItem 相同的“this”。我想出的解决方案只是在一个单独的变量中定义“this”,以便在map()内部使用。

render() {
var theApp = this;
return (
<div className="App">
<AddItem addItem={this.addItem.bind(this)} />
<ul>
{this.state.listItems.map(function(item,index){
return (
<ListItem id={index} key={index} title={item} removeItem={theApp.removeItem.bind(theApp)} />
);
})}
</ul>
</div>
);
}

我的问题是 - 我觉得我没有在其他人的代码或教程等中看到过这种方法,但我无法完全了解正在发生的事情以及更好的方法处理这个问题的方法。任何想法,甚至是有关谷歌内容的指示,非常感谢!

最佳答案

这称为上下文绑定(bind),您需要绑定(bind)正确的context,否则this关键字(指向React组件)将不可用在 map 内。你可以这样写:

1.通过使用箭头函数:

{   
this.state.listItems.map( (item,index) => {
return (
<ListItem id={index} key={index} title={item} removeItem={this.removeItem.bind(this)} />
);
})
}

2.通过将.bind(this)回调方法结合使用:

{   
this.state.listItems.map( function(item,index) {
return (
<ListItem id={index} key={index} title={item} removeItem={this.removeItem.bind(this)} />
);
}.bind(this))
}

建议:您应该在构造函数中绑定(bind)事件,而不是在render方法中绑定(bind)事件,它将避免在重新渲染期间创建新函数。

引用:https://stackoverflow.com/a/31296221/5185595

有关箭头函数的更多详细信息,请查看此答案:https://stackoverflow.com/a/34361380/5185595

关于javascript - 在 React 中,是否有比从映射中引用外部类更标准的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43331327/

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