gpt4 book ai didi

javascript - react : Retrieve dynamic child key upon event

转载 作者:行者123 更新时间:2023-12-03 13:05:19 25 4
gpt4 key购买 nike

我知道dynamic children组件的必须有一个唯一的key,如下所示(官方文档的修改示例):

render: function() {
var results = this.props.results;
return (
{results.map(function(result) {
return <ChildComponent type="text" key={result.id} changeCallback={this.props.callbackFn}/>;
})}
);
}

考虑到 ChildComponent 是嵌套在此处的另一个 React 组件,其 render 方法如下

render: function() {
var results = this.props.results;
return (
<div className="something">
<input type="text" onChange={this.props.changeCallback} />
</div>
);
}

调用callbackFn(event)时有什么方法可以访问该 key 吗?

最佳答案

尽管第一个答案是正确的,但这被认为是一种不好的做法,因为:

A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

更好的方法:

var List = React.createClass({
handleClick (id) {
console.log('yaaay the item key was: ', id)
}

render() {
return (
<ul>
{this.props.items.map(item =>
<ListItem key={item.id} item={item} onItemClick={this.handleClick} />
)}
</ul>
);
}
});

var ListItem = React.createClass({
render() {
return (
<li onClick={this._onClick}>
...
</li>
);
},
_onClick() {
this.props.onItemClick(this.props.item.id);
}
});

来源:https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md

关于javascript - react : Retrieve dynamic child key upon event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23448937/

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