使用钩子处理 react-native 中的动态复选框 [英] Handling dynamic checkbox in react-native using hooks

查看:47
本文介绍了使用钩子处理 react-native 中的动态复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实施 react-native-elements 复选框.在我的情况下,我需要基于数组有多个复选框.下面是我的代码 -

I'm trying implement react-native-elements checkbox. In my case i need to have multiple checkbox based on the array. Below is my code -

const CheckTest = () => {
    const [check, setCheck] = useState(false);
    const label = [
        {
            name: 'first'
        },
        {
            name: 'second'
        },
        {
            name: 'third'
        },
        {
            name: 'fourth'
        }]
    const onValueChange = () => {
        setCheck(check => !check)
    }
    return (
        <View style={{ paddingTop: 20 }}>
            {label.map(item => {
                return <CheckBox
                    title={item.name}
                    checked={check}
                    onPress={(val) => onValueChange(val)}
                    key={item.name}
                />
            })}


        </View>
    )
}

问题出在这段代码中,当我选择/取消选择一个复选框时,所有复选框都被选中/取消选中.

Problem is in this code is when i select/deselect one checkbox all checkbox are getting checked/unchecked.

我认为这是因为 check state 因为它适用于所有人.

I aasume this is happening because of check state as it is applying to all.

如何处理这个场景?

提前致谢!!!!!!

推荐答案

试试这个方法

const CheckTest = () => {
    const [data, setData] = useState([
        {
            name: 'first'
        },
        {
            name: 'second'
        },
        {
            name: 'third'
        },
        {
            name: 'fourth'
        }]); 



    const onValueChange = (item, index) => {
        const newData = [...data];
        newData[index].isCheck = !item.isCheck;
        setData(newData);
    }

    return (
        <View style={{ paddingTop: 20 }}>
            {data.map((item, index) => {
                return <CheckBox
                    title={item.name}
                    checked={item.isCheck || false}
                    onPress={(val) => onValueChange(item, index)}
                    key={item.name}
                />
            })}


        </View>
    )
}

这篇关于使用钩子处理 react-native 中的动态复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆