在React中,最佳实践是在父节点上放置一个onClick事件,并使用如下的event.target访问子级的属性。您如何在React Native中做到这一点?
handleClick = (event) => {
this.setState({
color: event.target.dataset.color
})
}
render(){
return(
<div onClick={this.handleClick}>
<div data-color="red"></div>
<div data-color="green"></div>
<div data-color="yellow"></div>
<div data-color="blue"></div>
<div data-color="gray"></div>
</div>
)
}
在React Native中,我发现如何执行此操作的唯一方法是为每个孩子添加一个onPress ...问题是:这是最佳实践吗?是否有更好的方法,例如添加数据属性并以某种方式访问它们?
handlePress = (color) => {
this.setState({
color
})
}
render(){
return(
<View>
<TouchableOpacity onPress={this.handlePress.bind(this, "red")}>
<View></View>
<TouchableOpacity/>
<TouchableOpacity onPress={this.handlePress.bind(this, "green")}>
<View></View>
<TouchableOpacity/>
<TouchableOpacity onPress={this.handlePress.bind(this, "yellow")}>
<View></View>
<TouchableOpacity/>
<TouchableOpacity onPress={this.handlePress.bind(this, "blue")}>
<View></View>
<TouchableOpacity/>
<TouchableOpacity onPress={this.handlePress.bind(this, "gray")}>
<View></View>
<TouchableOpacity/>
</View>
)
}