我正在尝试将按钮的id作为onPress事件触发的函数的参数传递。
setCategory = (e) => {
console.log(e.target.id)
}
render(){
return(
<Button title="News" id={15} onPress={this.setCategory}/>
)
}
因此15
应该在终端上登录,但是我正在获取undefined
。这就是我在Reactjs中要做的,但是我是React Native的新手,所以我不知道语法是否错误。
答案 0 :(得分:2)
如果id来自道具,那么您可以这样做。
<Button title="News" id={this.props.prop_where_id_is} onPress={() => this.setCategory(this.props.prop_where_id_is)} />
然后您的setCategory
变为
setCategory = (e) => {
console.log(e)
}
答案 1 :(得分:1)
您可以在“参考”的帮助下获取道具
<Button
id='5'
title='sss'
ref={ref => this.button = ref}
onPress={() => console.log(this.button.props.id)}
/>
以您的情况
onPress = (id) => {
console.log(id);
}
...
<Button
id='5'
title='sss'
ref={ref => this.button = ref}
onPress={() =>
this.onPress(this.button.props.id)
}
/>