React Checkbox not sending onChange

后端 未结 7 1361
夕颜
夕颜 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:45

    In the scenario you would NOT like to use the onChange handler on the input DOM, you can use the onClick property as an alternative. The defaultChecked, the condition may leave a fixed state for v16 IINM.

     class CrossOutCheckbox extends Component {
          constructor(init){
              super(init);
              this.handleChange = this.handleChange.bind(this);
          }
          handleChange({target}){
              if (target.checked){
                 target.removeAttribute('checked');
                 target.parentNode.style.textDecoration = "";
              } else {
                 target.setAttribute('checked', true);
                 target.parentNode.style.textDecoration = "line-through";
              }
          }
          render(){
             return (
                <span>
                  <label style={{textDecoration: this.props.complete?"line-through":""}}>
                     <input type="checkbox"
                            onClick={this.handleChange}
                            defaultChecked={this.props.complete}
                      />
                  </label>
                    {this.props.text}
                </span>
            )
        }
     }
    

    I hope this helps someone in the future.

    0 讨论(0)
提交回复
热议问题