I am mapping through an array, and I want my variable i
to be used as a unique key for my Components, however I do not know how (or where) to increment it correctly, if I add a {i++}
within the <Component>
tags then it will display the value of i
on screen, and if I instead add {this.function(i)}
and place the i++
inside the function, it will call the function but the variable i
will reinitiate to the value of 0
everytime, so the key value will not be unique.
(我正在通过数组进行映射,并且希望将变量i
用作组件的唯一键,但是,如果我在<Component>
内添加{i++}
,我不知道如何(或在哪里)正确地递增它<Component>
标记,它将在屏幕上显示i
的值,如果我改为添加{this.function(i)}
并将i++
放在函数内,它将调用该函数,但变量i
将重新初始化为0
的值每次,因此键值将不是唯一的。)
I need the value of i
to be the key for the component and it has to be incremented by 1 everytime, does anyone know how I can achieve this?(我需要i
的值作为组件的键,并且每次都必须将其递增1,有人知道我如何实现这一目标吗?)
Also, as you can see in the code, when the component is clicked it will make a function call which will send the value of i
of the clicked component as a parameter to the called function.(另外,如您在代码中所看到的,单击组件时,它将进行函数调用,该调用会将被单击组件的i
的值作为参数发送给被调用函数。)
Code:
(码:)
function(i) {
console.log(i)
}
render() {
var i = 0;
var {array} = this.state;
return (
<div className="App">
{array.map(item => (
<Component key={i} onClick={(e) => this.function(i, e)}>
<p>{item.name}</p>
</Component>
))}
</div>
);
}
ask by random1234 translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…