【问题标题】:react native - How to use React Hooks in array of tuples?react native - 如何在元组数组中使用 React Hooks?
【发布时间】:2021-11-24 06:25:41
【问题描述】:

我正在尝试制作从 const“值”读取数据并呈现复选框列表的 FlatList。对于复选框,我使用来自 react-native-paper 的 Checkbox.Android。

常量“值”包含以下数据:

const values = [
{
  name: 'Checkbox 1',
  [check, setCheck]: React.useState(false),      
},
{
  name: 'Checkbox 2',
  [check, setCheck]: React.useState(false), 
},
];

当我使用 const [check, setCheck] = React.useState(false); 时,React Hook 可以工作,但是如何将它放在“值”中?

我收到错误:

 Unexpected token, expected "]" 
  123 |     {
  124 |       name: 'Checkbox 1',
> 125 |       [check, setCheck]: React.useState(false),
  |                 ^
  126 |     },
  127 |     {]

抱歉,我是新来的,我找不到像这种情况下的任何复杂示例。 或者这是不可能的https://reactjs.org/docs/hooks-rules.html:

不要在循环、条件或嵌套函数中调用 Hooks

【问题讨论】:

  • 这几乎是不可能的。你应该只在 React 功能组件中使用钩子

标签: arrays reactjs react-native react-hooks tuples


【解决方案1】:

根据钩子规则这是不可能的。 但你可以这样做。

//your checkbox state
const [checkbox,setcheckbox] = useState([
{
  name: 'Checkbox 1',
  checked:false,      
},
{
  name: 'Checkbox 2',
  checked:false, 
},
]);

然后循环数据或使用flatlist

<Flatlist
    data={checkbox}
    renderItem={({item,index})=>{
        return (
            <Pressable onPress={()=>{
            let newcheckbox = checkbox;
            newcheckbox[index].checked = !checkbox[index].checked;
            setcheckbox(newcheckbox)
            }}>
            <Text style={{color:item?.checked ? 'green':'red'}}>
             {`${item?.checked ? 'Checked':'UnCheked'} (click me to change)`}
            <Text/>
            </Pressable>
        );
    }}

/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-07
    • 2019-10-17
    • 2019-07-13
    • 2021-01-05
    • 2020-08-10
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    相关资源
    最近更新 更多