How to set default Checked in checkbox ReactJS?

前端 未结 16 1984
难免孤独
难免孤独 2020-11-27 11:51

I\'m having trouble to update the checkbox state after it\'s assigned with default value checked="checked" in React.

var rCheck = React         


        
16条回答
  •  青春惊慌失措
    2020-11-27 12:38

    There are a few ways to accomplish this, here's a few:

    Written using State Hooks:

    function Checkbox() {
      const [checked, setChecked] = React.useState(true);
    
      return (
        
      );
    }
    
    ReactDOM.render(
      ,
      document.getElementById('checkbox'),
    );
    

    Here is a live demo on JSBin.

    Written using Components:

    class Checkbox extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isChecked: true,
        };
      }
      toggleChange = () => {
        this.setState({
          isChecked: !this.state.isChecked,
        });
      }
      render() {
        return (
          
        );
      }
    }
    
    ReactDOM.render(
      ,
      document.getElementById('checkbox'),
    );
    

    Here is a live demo on JSBin.

提交回复
热议问题