node.js - 反应本机中的复选框条件
问题描述
我试图在我的复选框上设置一个条件,我想为每个状态设置检查次数
所以这里我有我的 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()}
/>
)}
}
例如,这taille
是'M'
我只能检查 1 个 checkox 的状态,这种情况下我是否能够检查所有复选框,有什么解决方案吗?
解决方案
从你说的如果...
taille 的状态是 'M' 那么我只能检查 1 个 checkox ,这种情况下我能检查所有的复选框吗
那么代码是我处理这种情况的答案
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})
}
推荐阅读
- thymeleaf - Thymeleaf ..如何使用 th:replace 在一个页面之间传递参数到另一个页面
- java - YT 视频同步观看后台
- angular - Angular Material中的下拉菜单问题
- ios - VNDetectFaceLandmarksRequest 在带有 iOS 14 模拟器的 m1 mac 上不起作用?(未指定的错误)
- discord.js - discord.js 检查用户和机器人是否在同一个语音通道中
- c++ - 调试一个简单的函数
- algorithm - 算法求助:给定一个num,最后能不能是1
- python - 我无法通过 AWS SES 发送带有主题的电子邮件
- javascript - 删除滑动延迟香草js
- javascript - 未捕获的类型错误:$(...).popover 不是函数