React input checkbox select all component

后端 未结 3 1825
野的像风
野的像风 2021-01-02 16:19

I\'m trying to build a proper react input checkbox select all component. The idea is that there is a component and

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 17:14

    I think there could be some modifications to your implementation to achieve the desired results in a more React'esque form.

    What you should get rid of first, is the InputCheckboxAll checkbox class, and the allChecked prop of the InputCheckbox class. A checkbox is a relatively dumb element, it should not know about concepts such as Everything is selected.

    Instead, the checkbox should be implemented as an item that is simply either checked or unchecked.

    var InputCheckbox = React.createClass({
      getDefaultProps: function () {
        return {
          checked: false
        }
      },
      render: function () {
        return (
        
        )
      }
    })
    

    The state of your app (concepts such as All Selected) should be managed from the main App, keeping lower level elements stateless. The state of the main app can simply represent the checked status of each of your checkboxes:

      getInitialState: function () { 
          return {
            // 3 checkboxes, all initialized as unchecked
            checked: [false, false, false]
          }; 
      },
    

    Now, you can recreate the render function to draw 3 checkboxes, plus your select all checkbox. Each can be binded to its own data in the this.state.checked array. When the changes, we bind an index to the change handler, so we know which array element to modify.

      render: function () {
        // Recalculate if everything is checked each render, instead of storing it
        var isAllChecked = this.state.checked.filter(function(c) {
            return c;
        }).length === this.state.checked.length;
    
        return (
        
    Select All:



    ) }

    You don't need to store any state related to All Selected. Instead, it would be better to recalculate if everything is selected or not during every render. When the Select All checkbox is checked, we simply set every element of this.state.checked to true.

    This also has the advantage of when you manually select all the checkboxes, the select all checkbox will check itself.

    Here's a sample implementation: https://jsfiddle.net/rsupvxry/

提交回复
热议问题