我想找出所有已勾选其复选框的名称。我正在使用react-native-elements复选框。我的工作条件是最多需要检查4个元素,最少要检查1个元素。
也许这是一个微不足道的问题,但是我是本机反应的新手,我在网上搜索了所有内容,但无法解决。
共享我的代码以供参考:
import React, { Component } from 'react';
import { View, Text, TouchableOpacity, ScrollView, FlatList,
Alert } from 'react-native';
import { CheckBox } from 'react-native-elements'
class Categories extends Component{
state = {
enabled: false,
checked:[],
len: 0,
names: [],
data : [
{ "name": "Bagels",},
{ "name": "Bakery",},
{ "name": "Bar",},
{ "name": "Barns"},
{ "name": "Barcades"},
{ "name": "Beach",},
{ "name": "Beach Bar",},
{ "name": "Bistro",},
{ "name": "Brewery",},
{ "name": "Cafe",},
{ "name": "Comedy Clubs"},
{ "name": "Country Clubs"},
{ "name": "Co-Working Space"},
{ "name": "Dessert / Pastry",},
]
};
componentWillMount() {
let { data} = this.state;
let intialCheck = data.map(x => false);
this.setState({ checked: intialCheck })
}
handleChange = (index, name) => {
let checked = [...this.state.checked];
checked[index] = !checked[index];
this.setState({ checked });
if(checked[index] === true){
this.setState((prevState) => ({
len: prevState.len + 1
}), () => {
if(this.state.len >=1 ){
this.setState({enabled: true,})
}
if(this.state.len > 4){
checked[index] = false;
this.setState({checked, len: 4,}, () =>{
Alert.alert("Warning","You can't select more than 4
categories!");
});
}
})
}
if(checked[index] === false){
len: prevState.len - 1,
}), () => {
if(this.state.len <1){
this.setState({enabled: false})
}
})
}
}
render(){
let { data, checked } = this.state;
return(
<View style={{flex: 1}}>
<View style={{flex: 8.5}}>
<Text>Categories</Text>
<ScrollView>
<FlatList
data={data}
extraData={this.state}
renderItem={({ item, index }) =>
<CheckBox
title={item.name}
checkedIcon='circle'
uncheckedIcon='circle'
checkedColor='#DD9FDB'
uncheckedColor='#D8D8D8'
onPress={() => this.handleChange(index,
item.name)}
checked={checked[index]}
size={15}
/>
}
/>
</ScrollView>
</View>
</View>
);
}
}
我想知道所有的名字都被点击了。
感谢所有帮助!