我有一个组件将使用 map 来渲染多个复选框,每个复选框都有一个回调函数“onPress”通过 props 获取,“onPress”函数将 setState 选中,但是现在当我单击一个复选框时,将选择所有复选框,因为它们都使用相同的状态,目标我想选择我刚刚点击的每个复选框,我知道我可以为每个复选框编写许多状态不同的“onPress”函数,但它看起来很愚蠢,我会在未来,解决任务的最佳和灵活方法是什么?
import React, { Component } from 'react'
import { View } from 'react-native'
import { CheckBox } from 'react-native-elements'
const styles = {
CheckBox: {
borderBottomWidth: 0.3,
borderBottomColor: 'gray'
},
checkBox : {
backgroundColor: "#ffffff",
borderWidth: 0
},
text: {
flex: 0.95,
backgroundColor: "#ffffff"
}
}
const languages = ["中文","英文","日文","韓文"]
class Language extends Component {
constructor(props) {
super(props);
this.state = { checked: false };
}
onPress = () => {
this.setState({ checked: !this.state.checked })
}
renderlanguages = () => {
return languages.map((langauge) => {
return(
<View key = { langauge } style = { styles.CheckBox }>
<CheckBox
title = { langauge }
iconRight
containerStyle = { styles.checkBox }
textStyle = { styles.text }
checkedColor = 'red'
checked = { this.state.checked }
onPress = { this.onPress }
/>
</View>
)
})
}
render(){
return(
<View>
{ this.renderlanguages() }
</View>
)
}
}
export default Language;