react native中的复选框条件



im试图在我的checkboxs上设置一个条件,我想设置每个状态的检查次数

所以这里我有我的JSON文件,它有4个元素

[
{
"id": 0,
"key": "Viande hachee",
"checked": false,
"image": "https://i.imgur.com/RuVD8qi.png   "
},
{
"id": 1,
"key": "Escalope pane",
"checked": false,
"image": "https://i.imgur.com/WNeYn6d.png"
},
{
"id": 2,
"key": "Escalope grille",
"checked": false,
"image": "https://i.imgur.com/iFpCySw.png"
},
{
"id": 3,
"key": "Cordon  bleu",
"checked": false,
"image": "https://i.imgur.com/iRo6ivZ.png"
}
]
这是我的代码:
export default class Commande extends Component {
constructor(props) {
super(props)
this.state = {
data: TacosData,
SelectedItem: [],
taille: "M"
};
}
onchecked(id) {
const data = this.state.data
const index = data.findIndex(x => x.id === id);
data[index].checked = !data[index].checked
this.setState(data)
}
renderTacos(item, key) {
return (
<TouchableOpacity style={{ alignItems: 'center', marginLeft: normalize(20), marginRight: normalize(20 )}} key={key} onPress={() => { this.onchecked(item.id) }}>
<Image style={styles.rednerImg} source={{ uri: item.image }} ></Image>
<Text style={styles.rednertext}>{item.key}</Text>
<CheckBox value={item.checked}
style={{ transform: [{ scaleX: 0.8 }, { scaleY: 0.8 }], }}
onValueChange={() => { this.onchecked(item.id) }}
tintColors={{ true: '#D05A0B', false: 'black' }}
/>
</TouchableOpacity>
)
}
render() {
return (
<FlatList
data={this.state.data}
style={{ width: '100%', height: '100%', }}
numColumns={2}
renderItem={({ item }) => this.renderTacos(item)}
keyExtractor={(item, index) => index.toString()}
/>
)}
}

例如,如果CCD_ 1的状态是CCD_,这种情况下我能勾选所有的复选框吗有什么解决办法吗?

根据您所说的如果…

taille的状态是‘M’,那么我只能检查1个复选框,是这种情况下,我可以检查的所有复选框

那么代码就是我处理这种情况的答案

onchecked(id) {
const data = this.state.data
const index = data.findIndex(x => x.id === id)
if (this.state.taille == 'M') {
for(const i = 0; i < data.length; i++) {
if (i != index) {
data[i].checked = false // reset other checkboxes to unchecked, so when taille is 'M' only clicked checkbox that can be true
}
}
}
data[index].checked = !data[index].checked
this.setState({data})
}

根据以下评论编辑响应案例

onchecked(id) {
const data = this.state.data
const index = data.findIndex(x => x.id === id)

let maxCheck = undefined
if (this.state.taille == 'M') {
maxCheck = 1
} else if (this.state.taille == 'L') {
maxCheck = 2
}
let checkboxCheckedTotal = 0
for(const i = 0; i < data.length; i++) {
if (data[i].checked) {
checkboxCheckedTotal++
}
}
if (maxCheck == undefined || data[index].checked || checkboxCheckedTotal < maxCheck) {
data[index].checked = !data[index].checked
}
this.setState({data})
}

最新更新