React事件处理程序显示相同的索引值



有一个简单的React组件,它显示一个字符,单击时应该调用一个处理程序,并提供一个数字。该组件被调用多次,因此显示为列表。有趣的是,当调用处理程序时,提供的索引总是相同的,即i+1的最后一个值。就好像使用了i的引用,而不是值。

我知道有一个javascript映射函数,但这种方法不应该也起作用吗?

const charComp = (props) => {
return (
<div onClick={props.clicked}>
<p>{props.theChar}</p>
</div>
);

deleteHandler = (index) => {
alert(index);
}
render() {
var charList = []; // will later be included in the output
var txt = "some text";
for (var i=0; i< txt.length; i++)
{
var comp = 
<CharComponent
theChar = {txt[i]}
clicked = {() => this.deleteHandler(i)}/>;
charList.push(comp);      
}

因为当你点击一个字母时,i已经是9了,它将保持9,因为信息没有保存在任何地方。如果要跟踪索引,则应将其传递给子组件CharComponent,然后在单击时将其传递回父组件。

const CharComponent = (props) => {
const clickHandler = () => {
props.clicked(props.index);
}
return (
<div onClick={clickHandler}>
<p>{props.theChar}</p>
</div>
);
};
var comp = (
<CharComponent theChar={txt[i]} index={i} clicked={(index) => deleteHandler(index)} />
);

你的一个小代码沙盒

最新更新