【问题标题】:how to Uncheck Checkbox.Group in Antd React.js如何在 Antd React.js 中取消选中 Checkbox.Group
【发布时间】:2019-11-03 19:19:25
【问题描述】:

我有以下代码使用https://ant.design/components/checkbox/,并尝试在选中复选框时取消选中。 如果单击按钮,我不想检查全部,只需取消选中全部或选中的一个复选框。

constructor(props) {
        super(props);
        this.state = {
            checked: true,
        }
        this.onChange = this.onChange.bind(this);
    }


    onChange(value) {
        this.props.onChangeSession(value)
    }

    onChangeBox = e => {
        this.setState({
            checked: e.target.checked,
        });
    };

    unChecked = () => {
        this.props.onChangeSession([])
        this.setState({
            checked: false
        });
    };


    render () {
        const {
            data,
        } = this.props
        return  (
            <div>
                <Button type="primary" size="small" onClick={this.unChecked}>
                   Uncheck
                </Button>
                <Checkbox.Group 
                    style={{ width: '100%' }} 
                    onChange={this.onChange}>
                    <div>
                        <div className="filter-subhead">Track</div>

                        {data.map(i => 
                            <div className="filter-item">
                                <Checkbox
                                checked={this.state.checked}
                                onChange={this.onChangeBox}
                                value={i}>{i}</Checkbox>
                            </div>
                        )}                     
                    </div>
                </Checkbox.Group> 
            </div>

        )
    }

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript reactjs antd ant-design-pro


    【解决方案1】:

    Working Link

    由于Checkbox.Group,复选框上的切换不起作用,您可以简单地使用Checkbox


    关于复选框状态:

    您不能为所有复选框使用一个 state,因此您需要有一个 bool 数组作为每个复选框项的状态。

    在示例中,我在 componentDidMount 上初始化了复选框状态,它创建了一个数组 ([false,false,false,...]),并且在 Uncheck 上使用完全相同的东西进行重置。 (在我的代码中重构的可能性

    用户分配的状态将决定是否选中复选框。

    import React from "react";
    import ReactDOM from "react-dom";
    import { Button, Checkbox } from "antd";
    import "antd/dist/antd.css";
    import "./index.css";
    
    let data = [3423, 3231, 334234, 55345, 65446, 45237];
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          checkboxArray: []
        };
        // this.onChange = this.onChange.bind(this);
      }
    
      componentDidMount() {
        let createEmptyArray = new Array(data.length).fill(false);
        this.setState({ checkboxArray: createEmptyArray });
      }
    
      onChange(e) {
        console.log(e.target);
      }
    
      onChangeBox = (e, i) => {
        let checkBoxCurrentState = this.state.checkboxArray;
        checkBoxCurrentState[i] = !checkBoxCurrentState[i];
        this.setState({
          checkboxArray: checkBoxCurrentState
        });
      };
    
      unChecked = e => {
        let resetArray = new Array(data.length).fill(false);
        this.setState({
          checkboxArray: resetArray
        });
      };
    
      render() {
        const { data } = this.props;
        return (
          <div>
            <Button type="primary" size="small" onClick={this.unChecked}>
              Uncheck
            </Button>
    
            <div>
              <div className="filter-subhead">Track</div>
              {data.map((i, index) => (
                <div className="filter-item">
                  <Checkbox
                    checked={this.state.checkboxArray[index] ? true : false}
                    onChange={e => this.onChangeBox(e, index)}
                    value={index}
                  >
                    {JSON.stringify(this.state.checkboxArray[index])}
                  </Checkbox>
                </div>
              ))}
            </div>
            {JSON.stringify(this.state.checkboxArray)}
          </div>
        );
      }
    }
    
    ReactDOM.render(<App data={data} />, document.getElementById("root"));
    

    简单的复制粘贴上面的代码,在需要的地方添加props。

    如果你想使用Checkbox.Group,则需要更新CheckBox.Group的onChange方法

    let data = ['Apple', 'Pancakes', 'Butter', 'Tea', 'Coffee'];
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          checkboxArray: []
        };
        // this.onChange = this.onChange.bind(this);
      }
    
      componentDidMount() {
        let createEmptyArray = new Array(this.props.data.length).fill(false);
        this.setState({ checkboxArray: createEmptyArray });
      }
    
      onChangeBox = (e, i) => {
        let checkBoxCurrentState = this.state.checkboxArray;
        checkBoxCurrentState[i] = !checkBoxCurrentState[i];
        this.setState({
          checkboxArray: checkBoxCurrentState
        });
      };
    
      unChecked = () => {
        let resetArray = new Array(data.length).fill(false);
        this.setState({
          checkboxArray: resetArray
        });
      };
    
      render() {
        const { data } = this.props;
        return (
          <div>
            <button onClick={this.unChecked}>Clear All</button>
            {this.props.data.map((single, index) => (
              <div>
                <input
                  type="checkbox"
                  id={index}
                  name="scales"
                  checked={this.state.checkboxArray[index]}
                  onChange={e => this.onChangeBox(e, index)}
                />
                <label for={index}>{single}</label>
              </div>
            ))}
          </div>
        );
      }
    }
    
    ReactDOM.render(<App data={data} />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

    • 是的,这正是我面临的问题。我知道我可以通过 onChangeBox 访问 e.target.checked,但仍然不确定如何将 false 设置为选中。仅使用 react 可能是一个不错的选择。不过,我仍然想弄清楚如何使用 antd 来做到这一点。谢谢@DhavalJardosh!
    • @Mandoxsy,检查我的编辑,删除了Checkbox.Group,一切正常,你应该采用这种方法。
    • 这太棒了!是的,如果我们删除 checkbox.group,我看到检查工作正常。我使用 checkbox.group 的原因是因为我有多个具有不同值的 ,并且必须传递和选择所有值的数组以便以后过滤它。我仍然可以使用这种方法并将选择的值添加到数组中以发送所有选择的值吗?
    • 我不确定,但是您可以尝试一下,如果有任何问题我们一定可以解决。
    【解决方案2】:

    如果您打算使用map 动态生成复选框,那么使用状态来跟踪选中的值将会很棘手。你不应该这样做。

    您应该做的就是在组件中完全不包含 checked 属性。

    <Checkbox
        onChange={this.onChangeBox}
        value={i}>{i}
    </Checkbox>
    

    即使您不包含选中的属性,该复选框仍应选中。这有点奇怪,我知道。

    只需将值传递给 onChangeBox 函数并在那里处理所有逻辑并设置更改时的状态值。

    我刚刚测试了它,它可以工作。

    【讨论】:

    • 谢谢@NicholasPorter!我明白你所说的不包括检查的意思。我仍然可以看到已签入 onChangeBox -> e.target.checked。当我触发toggleChecked() 时,我仍然不确定如何将所有复选框的 e.target.checked 设置为 false。你能帮忙吗?谢谢!
    猜你喜欢
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2017-10-22
    • 2014-10-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多