【问题标题】:why other element hide after checkbox checked in react js?为什么在反应js中选中复选框后隐藏其他元素?
【发布时间】:2020-08-25 11:47:12
【问题描述】:

我做了一个checkbox 的简单演示。我还在我的父组件上实现了onchange handler。但是当我检查first parent 时遇到了一个问题,它隐藏了其他parents

这是我的第一个状态

在第一个父母checked之后隐藏其他父母

https://codesandbox.io/s/lucid-fire-cxp9c?file=/src/App.js

其次我无法检查child checkbox。实际上我的recursion 函数有问题

const setChecked = (data, label) => {
  // grab the first element
  console.log(data);

  const [current, ...rest] = data;

  return current && current.label === label
    ? [
        {
          ...current,
          checked: !current.checked,
          ...rest
        }
      ]
    : [current, ...setChecked(rest, label)];
};

这是我的全部代码

https://codesandbox.io/s/lucid-fire-cxp9c?file=/src/App.js:642-970

【问题讨论】:

    标签: javascript reactjs recursion


    【解决方案1】:

    这应该可以,希望下面的代码是不言自明的。

    const setChecked = (data, label) => {
      return data.map((currData) => {
        const { childrens } = currData;
        const hasChildren = childrens && childrens.length > 0;
    
        if (currData.label === label) {
          return { ...currData, checked: !currData.checked };
        }
    
        if (hasChildren) {
          return { ...currData, childrens: setChecked(childrens, label) };
        }
    
        return currData;
      });
    };
    

    为避免Warning: A component is changing an uncontrolled input...,在将checked 属性传递给复选框时使用i.checked === true

    ...
    <input
      type="checkbox"
      checked={i.checked === true} // here
      onChange={() => {
        handleChange(i);
        setTimeout(ab, 2000);
      }}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2017-06-23
      • 2021-05-08
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多