【问题标题】:How to handle the state of multiple checkboxes in child component by the parent in react?react如何处理子组件中多个复选框的状态?
【发布时间】:2020-03-24 01:21:42
【问题描述】:

我有多个动态复选框。这些复选框被放置(假设)在“B”组件中。 我已经在“B”的父级“A”组件中管理了这些复选框的状态。 当一个或所有复选框被点击时,我想渲染一个 div

预期结果:如果单击一个或所有复选框,则呈现 div。如果没有选择,则应该隐藏 div。基本上,即使选中了一个复选框,div 也应该是可见的。

当前结果:当点击一个复选框时,会呈现 div,但如果选中另一个复选框,则 div 会消失。

这是我的 A 组件(父级)

const A = () => {
   const [isChecked, setIsChecked] = useState(false) // state that holds state of check boxes 

   return (
      {isChecked ? <div>Some Content..</div> : null} // rendering the div according to the state of the checkboxes

      <Child isChecked={isChecked} setIsChecked={setIsChecked} />
  ) 
}

子组件代码

 const Child = props => {
      
        return (
           {checkBoxList.map((box, index) => (
              <CustomCheckBox
                 key={index}
                 name={`check-box-${index}`}  // to uniquely identify each check box 
                 isChecked={props.isChecked}
                 setIsChecked={props.setIsChecked} />
           ))}
        )
    }

CustomCheckBox 组件:

 const CustomCheckBox = props => {
    
      const onChangeHandler = (event) => {
         props.isChecked ? props.setIsChecked(false) : props.setIsChecked(true)
      }
    
      return <input name={props.name} type="checkBox" onChange={onChangeHandler} />;
 };
    
  CustomCheckBox.propTypes = {
    name: string
  }

我知道父组件状态现在只能处理一个复选框。

当前结果的原因是因为我在onChangeHandler函数中包含的条件。

  props.isChecked ? props.setIsChecked(false) : props.setIsChecked(true)

我对如何在上述场景中使用单个处理函数处理多个复选框的状态感到困惑!

【问题讨论】:

    标签: reactjs checkbox react-props react-component conditional-rendering


    【解决方案1】:

    您可以跟踪您单击的复选框索引,而不是如果它被单击了

    const [isChecked, setIsChecked] = useState([]) // state that holds state of checked boxes 
    

    那么处理程序将变为:

    const onChangeHandler = (index) => {
    
        const result = props.isChecked;
        var i = result.indexOf(index);
        if (i> -1) {
            result.splice(i, 1);
        }
        else {
            result = [...result, index]
        }
        props.setIsChecked(result)
      }
    

    所以在父母中你会检查 isChecked.length> 0

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 2019-02-08
      • 2022-01-14
      • 2016-09-11
      • 1970-01-01
      • 2020-12-21
      相关资源
      最近更新 更多