以这个简单的方式在 ReactJs 中创建列表组件:
for (var key in this.props.code_values)
{
var current = this.props.code_values[key];
var current_value = current.value;
drop_choices.push(<ListItem
button
key = { current.id }
onClick = {(event) => this.makeSomethingWithValue(current_value)}
>
{ current.value }
</ListItem>);
}
问题是 current_value 是在 Click 上计算的,因此它将始终等于迭代的最后一个 current_value。
例如:
code_values = [ { id : 1, value : 1}, { id : 2, value : 2} ]
点击“1”将得到“2”。
我们不是“创建”html satic 代码,而是一个组件,并且 OnClick 不是在此迭代期间“创建”为属性,而是仅在 onClick 事件之后“处理”。
最佳答案
这是 var 的作用域问题,请尝试使用 let
和 const
代替
for (let key in this.props.code_values)
{
const current = this.props.code_values[key];
const current_value = current.value;
drop_choices.push(<ListItem
button
key = { current.id }
onClick = {(event) => this.makeSomethingWithValue(current_value)}
>
{ current.value }
</ListItem>);
}
关于Javascript - 迭代期间使用值而不是引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53045064/