React Checkbox not sending onChange

后端 未结 7 1360
夕颜
夕颜 2020-12-04 16:19

TLDR: Use defaultChecked instead of checked, working jsbin.

Trying to setup a simple checkbox that will cross out its label text when it is checked. For some reason

相关标签:
7条回答
  • 2020-12-04 16:30

    onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.

    <input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;
    
    0 讨论(0)
  • 2020-12-04 16:36

    If you have a handleChange function that looks like this:

    handleChange = (e) => {
      this.setState({
        [e.target.name]: e.target.value,
      });
    }
    

    You can create a custom onChange function so that it acts like an text input would:

    <input
      type="checkbox"
      name="check"
      checked={this.state.check}
      onChange={(e) => {
        this.handleChange({
          target: {
            name: e.target.name,
            value: e.target.checked,
          },
        });
      }}
    />
    
    0 讨论(0)
  • 2020-12-04 16:39

    To get the checked state of your checkbox the path would be:

    this.refs.complete.state.checked
    

    The alternative is to get it from the event passed into the handleChange method:

    event.target.checked
    
    0 讨论(0)
  • 2020-12-04 16:39

    In material ui, state of checkbox can be fetched as

    this.refs.complete.state.switched
    
    0 讨论(0)
  • 2020-12-04 16:44

    It's better not to use refs in such cases. Use:

    <input
        type="checkbox"
        checked={this.state.active}
        onClick={this.handleClick}
    />
    

    There are some options:

    checked vs defaultChecked

    The former would respond to both state changes and clicks. The latter would ignore state changes.

    onClick vs onChange

    The former would always trigger on clicks. The latter would not trigger on clicks if checked attribute is present on input element.

    0 讨论(0)
  • 2020-12-04 16:44

    In case someone is looking for a universal event handler the following code can be used more or less (assuming that name property is set for every input):

        this.handleInputChange = (e) => {
            item[e.target.name] = e.target.type === "checkbox" ? e.target.checked : e.target.value;
        }
    
    0 讨论(0)
提交回复
热议问题