在 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>
)
}
Run Code Online (Sandbox Code Playgroud)
在 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>
)
}
Run Code Online (Sandbox Code Playgroud)
您可以为您的内部视图创建一个组件。像这样的东西:
const InnerComp = (props) => {
const customColor = props.color;
return <TouchableOpacity
onPress={()=>props.onPress(customColor)}>
<View style={{backgroundColor: customColor}}/>
<TouchableOpacity/>;
};
Run Code Online (Sandbox Code Playgroud)
然后你的主要组件将如下所示:
handlePress = (color) => {
this.setState({
color
})
}
render(){
return(
<View>
<InnerComp onPress={handlePress} color="red"/>
<InnerComp onPress={handlePress} color="green"/>
<InnerComp onPress={handlePress} color="yellow"/>
<InnerComp onPress={handlePress} color="blue"/>
<InnerComp onPress={handlePress} color="gray"/>
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
205 次 |
| 最近记录: |