だから私はreactnativeelementsチェックボックスを使用しているプロジェクトに取り組んでいます、そして私はついにそれがフェッチされたすべてのアイテムを一度に選択しないところでそれを機能させました。一度に1回だけ選択し、別のアイテムを選択しようとすると、最初のアイテムの選択が解除され、2番目のアイテムが選択されます。しかし、今では一度に複数のアイテムを選択することはできません。このプラットフォームでgoogleを検索しましたが、redditも検索しましたが、解決策が見つかりません。
これが私のコードです
constructor(props) {
super(props);
this.state = {
dataSource: [],
checked: null,
}
}
render() {
const { navigation } = this.props;
const cust = navigation.getParam('food', 'No-User');
const other_param = navigation.getParam('otherParam', 'No-User');
const cust1 = JSON.parse(cust);
const data = cust1;
console.log(data);
return (
<View style={styles.container}>
<BackButtonMGMT navigation={this.props.navigation} />
<FlatList
data={data}
extraData={this.state}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => (
<CheckBox
center
titleProps={{ color: 'black', fontWeight: 'bold'}}
title={item}
iconRight
checked={this.state.checked == item}
size={30}
onPress={() => this.setState({checked: item})}
containerStyle={styles.checkBox}
/>
)}
/>
</View>
)
}
CheckBox内のチェックされた行を変更しようとしました。check = {!! item.checked}を試しましたが、機能しません。check = {!this.state.checked}を試しましたが、これも機能しません。誰かがこの問題に遭遇しましたか?もしそうなら、どのようにこれを解決しましたか?
現在、状態にはchecked
、アイテムのチェックされた状態を格納する1つのパラメーターがあります。つまり、別のチェックボックスを選択するたびに、前の選択が失われます。複数の選択を許可するには、チェックボックスの状態の配列を管理する必要があります。これはさまざまなアプローチで実現できます。これが私が提案するアプローチです。
まず、コンストラクターを変更する必要があります
constructor(props) {
super(props);
const { navigation } = props;
const cust = navigation.getParam('food', 'No-User');
const other_param = navigation.getParam('otherParam', 'No-User');
const cust1 = JSON.parse(cust);
//Here we will make array of object with additional parameter, checked
//This assume cust1 will be ["Pecan Cookies", "Strawberry Cheesecake"]
const data = cust1.map(item=>({label:item, checked:false});
this.state = {
dataSource: [],
data,
checked: null,
}
}
それでは、レンダリング関数を更新しましょう
onChecked = (index) => {
let {data} = this.state;
data[index].checked = !data[index].checked;
this.setState({data})
}
render() {
const { data} = this.state;
return (
<View style={styles.container}>
<BackButtonMGMT navigation={this.props.navigation} />
<FlatList data={data} extraData={this.state} keyExtractor={(item, index)=> index.toString()}
renderItem={({ item, index }) => (
<CheckBox center titleProps={{ color: 'black', fontWeight: 'bold'}} title={item.label} iconRight
checked={item.checked} size={30} onPress={()=>this.onChecked(index)}
containerStyle={styles.checkBox}
/>
)}
/>
</View>
)
}
これにより、問題が解決するか、複数選択できるはずです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加