连接 JSX 视图时的 onPress 参数值不正确
Incorrect onPress Parameter Value When JSX views are Concatinated
我在 React Native 中呈现了一小部分行。每行包含一些信息和按钮,这些信息和按钮对关联的对象执行操作。
为了呈现行,我遍历了一个列表,并在每个新行中将 JSX 标记添加到一个数组中。
for (i = 0; i < this.state.values.length; i++) {
var theVariable = this.state.values[i].id;
returnValue.push(
<View style={{flexDirection: 'column', borderTopWidth: .5, borderColor: 'grey'}}
<View style={[s.rowStyle, {justifyContent: 'center'}]}>
<TouchableHighlight style={s.buttonOutlineActiveRental} underlayColor='transparent' onPress={() => this._someFunction(theVariable)}>
<Text style={s.buttonText}>
Click me!
</Text>
</TouchableHighlight>
</View>
</View>
);
}
问题是按下时函数的 theVariable
值不正确。通过一些调试,我发现 theVariable
总是等于最后一行中的 theVariable
。这让我相信每一行总是指向变量的最新版本。
在这种情况下,通过按下功能传递参数的正确方法是什么?
首先,我建议将 var
更改为 let
。其次将声明移出循环。
接下来为 "row" 创建一个新组件。将变量作为道具传递给行。这应该将当前值绑定到解决您问题的组件。
我在 React Native 中呈现了一小部分行。每行包含一些信息和按钮,这些信息和按钮对关联的对象执行操作。
为了呈现行,我遍历了一个列表,并在每个新行中将 JSX 标记添加到一个数组中。
for (i = 0; i < this.state.values.length; i++) {
var theVariable = this.state.values[i].id;
returnValue.push(
<View style={{flexDirection: 'column', borderTopWidth: .5, borderColor: 'grey'}}
<View style={[s.rowStyle, {justifyContent: 'center'}]}>
<TouchableHighlight style={s.buttonOutlineActiveRental} underlayColor='transparent' onPress={() => this._someFunction(theVariable)}>
<Text style={s.buttonText}>
Click me!
</Text>
</TouchableHighlight>
</View>
</View>
);
}
问题是按下时函数的 theVariable
值不正确。通过一些调试,我发现 theVariable
总是等于最后一行中的 theVariable
。这让我相信每一行总是指向变量的最新版本。
在这种情况下,通过按下功能传递参数的正确方法是什么?
首先,我建议将 var
更改为 let
。其次将声明移出循环。
接下来为 "row" 创建一个新组件。将变量作为道具传递给行。这应该将当前值绑定到解决您问题的组件。