React Checkbox not sending onChange

后端 未结 7 1409
夕颜
夕颜 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 (
                
                  
                    {this.props.text}
                
            )
        }
     }
    

    I hope this helps someone in the future.

提交回复
热议问题