Javascript 用按钮传递值
我在数组中有我的DB值Javascript 用按钮传递值,javascript,react-native,Javascript,React Native,我在数组中有我的DB值 "ExercisesData": [ { "Id": "01", "Reps": "10", "StartDate": "2019-06-20", "EndDate": "2019-06-21", "Notes&quo
"ExercisesData": [
{
"Id": "01",
"Reps": "10",
"StartDate": "2019-06-20",
"EndDate": "2019-06-21",
"Notes": "...."
},
{
"Id": "02",
"Reps": "1",
"Notes": "....."
},
{
"Id": "03",
"Reps": "150",
"Notes": "......"
}
]
我获取这些值并为它们创建一个按钮。像这样:
checkAttività (){
//.....
}
render() {
const exercises = this.state.Exercises.map(exercise => {
return (
<View>
<Text style={{ fontSize: 15 }}>Id: {exercise.Id}</Text>
<Text style={{ fontSize: 15 }}>Reps: {exercise.Reps}</Text>
<Text style={{ fontSize: 15 }}>Note: {exercise.Notes}</Text>
<TouchableOpacity
style={[styleButton.button, styleButton.buttonOK]}
onPress={() => this.checkAttività(exercise.Id)}>
<Text style={styleButton.buttonTesto}>Choose</Text>
</TouchableOpacity>
</View>
checkAttivitá(){
//.....
}
render(){
const exercises=this.state.exercises.map(exercise=>{
返回(
Id:{exercise.Id}
代表:{exercise.Reps}
注意:{exercise.Notes}
this.checkAttivitá(exercise.Id)}>
选择
通过这种方式,我为数组中的每个值创建了一个按钮。我应该做的是创建一个按钮,允许我传递与单击的键对应的id值。从某种意义上说:
身份证号码:01
代表:
注:
按钮1
身份证号码:02 代表: 注: 按钮2
如果单击按钮1,我将传递Id(01)的值。我该怎么做?谢谢。您可以这样做。只需绑定事件,就可以传递任何参数
onPress={ this.someEvent.bind(this,exercise.Id)}
someEvent(id){
console.log("You will get the id: ",id);
}
只需在
checkAttivitá
中添加id
参数,如下所示:
checkAttività (id){
//.....
}
您已经使用了匿名函数,因此它应该执行以下操作:
onPress={() => this.checkAttività(exercise.Id)}
此外,还应绑定事件,例如在构造函数中:
this.checkAttività = this.checkAttività.bind(this)
上面的代码看起来很好,您有任何错误吗?仅供参考,我将
this.state.Exercises
更改为this.state.exerciseData
我不建议使用非ascii名称,尽管checkAttivitá
@JuniusL。我已尝试在控制台日志中打印函数checkAttivitá中的id,但它不打印任何您需要的内容函数的d参数,看我们也可以这样做,它工作得非常好。绑定不需要只在构造函数中完成。“bind()方法创建一个新函数”-您不应该在每个onPress
中创建新函数。虽然我知道这是可行的,但您应该遵循良好的实践。或者,使用箭头函数。是的,我同意您的看法,因为这可能是性能问题,不被视为良好实践。感谢@Dan提醒。