【问题标题】:React Native Elements Checkbox keeps selecting all items instead of the one item this is selectedReact Native Elements Checkbox 一直选择所有项目,而不是选中的一项
【发布时间】:2020-09-18 20:09:24
【问题描述】:

希望一切都好,希望每个人都有一个美好而安全的周末。我需要一点帮助。我已经坚持了一周了。我有一个反应原生项目,我在其中使用一个带有反应原生元素复选框的平面列表。我有显示从我的数据库中获取的数据的平面列表。所以一切正常。但是当我检查正在显示的项目之一时,它会检查所有项目。我已经用谷歌搜索并尝试了几种不同的方法,我也从这里得到了这些方法。在复选框中没有选中任何内容或全部选中。你们可以看看我下面的代码,如果我遗漏了什么,请告诉我?

非常感谢!!!

import React from 'react';
import {
    View,
    Text,
    FlatList,
    StyleSheet, 
} from 'react-native';

import {
    ListItem,
    CheckBox,
} from 'react-native-elements';
import BackButtonMGMT from '../Components/BackButtonMGMT';

export default class ViewCategory extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            checked: false,
        }
    }

    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}
                        size={30}
                        onPress={() => this.setState({checked: !this.state.checked})}
                        containerStyle={styles.checkBox}
                        //bottomDivider
                        //chevron
                        />
                        
                    )}
                />

            </View>
        )
    }

    onCheck = (item) => {
        this.setState((state) => ({
            checked: !state.checked,
        }));
    }
}

【问题讨论】:

    标签: javascript react-native checkbox react-native-flatlist react-native-elements


    【解决方案1】:

    您当前将列表中的复选框设置为checked={this.state.checked}

    您似乎没有使用 onCheck 方法,而是在 onPress 中处理事件。因此,当您的 onPress 事件处理程序触发时,它会切换整个列表,因为列表中的每个项目都使用相同的状态。

    相反,您需要跟踪数组处于选中状态的所有项目。您将需要执行以下操作:

    this.state = {
      items: [],
      ... // other state
    }
    
    ...
    renderItem={({ item }) => (
      <CheckBox
        checked={!!item.checked} // <-- individual item checked state here
        onPress={() => {
          const items = [...this.state.items] // <-- shallow copy to show we're not mutating state
          const currentItemIndex = items.findIndex(v => v.name === item.name) // <-- lookup by something unique on the item like an ID. It's better to lookup rather than assume the array indexes are ordered the same.
          items[currentItemIndex].checked = !items[currentItemIndex].checked
          this.setState(state => ({ ...state, items }))
        }}
        ... // other props
      />
    )}
    

    【讨论】:

    • 抱歉回复晚了,度过了一个疯狂的周末,现在才回到这个话题。我将使用它,看看它是否有效。我会在几分钟内更新你。
    • 它给了我一个 TypeError: underfined is not an object.
    • @Jca39A 您是否在此处更新了这一行? const currentItemIndex = items.findIndex(v =&gt; v.name === item.name)我不知道您的数据模型是什么,因此您需要更新此行以匹配唯一字段。提供的示例假设您的数据模型类似于:[{name: 'foo'}, {name: 'bar'}] 然后 `v.name === item.name` 会起作用。如果不是,它将返回未定义。因此,您只需更新表达式以匹配数据模型中的唯一字段。
    • 仍然收到相同的错误消息。我的数据模型是 {[itemname: 'cookies']}。就是说这一行....items[currentItemIndex].checked = !items[currentItemIndex].checked.....是错误。我的 onPress 与您在上面的完全一样。但这就是我改变它的方式......我认为它也是错误的。 const currentItemIndex = items.findIndex(v => v.name === item.itemname)
    • 现在我确实让它在一次只检查一个的地方工作。我将检查状态更改为 this.state ={ checked: null,} 然后我将 CheckBox 中的检查更改为 ....checked={this.state.checked === item}。所以它正在工作,但它不允许我一次选择多个项目。如果我选择一个项目,然后尝试选择另一个。它将取消选择我首先选择的项目,然后选择新项目。你以前见过这种情况吗?
    【解决方案2】:

    这就是我解决它的方法,但现在我无法一次选择多个项目。

    export default class ViewCategory extends React.Component {
    
        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>
            )
        }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      相关资源
      最近更新 更多