Jak ustawić domyślne pole wyboru checkbox ReactJS?

Mam problem z zaktualizowaniem stanu checkboxa po przypisaniu domyślnej wartości checked= "checked" w Reaccie.

var rCheck = React.createElement('input',
                                 {type: 'checkbox', checked:'checked', value: true},
                                 'Check here');

Po przypisaniu checked="checked" nie mogę wejść w interakcję ze stanem pola wyboru, klikając, aby odznaczyć/sprawdzić.

Author: jww, 2015-08-24

8 answers

Aby wejść w interakcję z polem, musisz zaktualizować stan pola wyboru po jego zmianie. Aby mieć domyślne ustawienie, możesz użyć defaultChecked.

Przykład:

<input type="checkbox" defaultChecked={this.state.chkbox} onChange={this.handleChangeChk} />
 120
Author: nitishagar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-06 08:09:23

Jeżeli pole wyboru jest utworzone tylko z React.createElement wtedy właściwość defaultChecked jest używany.

React.createElement('input',{type: 'checkbox', defaultChecked: false});

Kredyt dla @nash_ag

 40
Author: Yarin Nim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-19 12:08:13

Jest kilka sposobów, aby to osiągnąć, oto jeden:

Napisane w ES6:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isChecked: true,
    };
  }
  toggleChange = () => {
    this.setState({
      isChecked: !this.state.isChecked,
    });
  }
  render() {
    return (
      <label>
        <input type="checkbox"
          checked={this.state.isChecked}
          onChange={this.toggleChange}
        />
        Check Me!
       </label>
    );
  }
}

ReactDOM.render(<Checkbox />, document.getElementById('checkbox'));

Oto demo na JSBin .

Lub ze zwykłym starym JavaScript:

var Checkbox = React.createClass({
  getInitialState: function() {
    return {
      isChecked: true
    };
  },
  toggleChange: function() {
    this.setState({
      isChecked: !this.state.isChecked // flip boolean value
    }, function() {
      console.log(this.state);
    }.bind(this));
  },
  render: function() {
    return (
      <label>
        <input
          type="checkbox"
          checked={this.state.isChecked}
          onChange={this.toggleChange} />
        Check Me!
      </label>
    );
  }
});

React.render(<Checkbox />, document.getElementById('checkbox'));

Ponownie, z demo na żywo na JSBin .

 33
Author: Jon Saw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-30 07:02:36

Oprócz poprawnej odpowiedzi możesz po prostu zrobić: P

<input name="remember" type="checkbox" defaultChecked/>
 8
Author: Fareed Alnamrouti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-21 07:58:35

To działa

<input type="checkbox" value={props.key} defaultChecked={props.checked} ref={props.key} onChange={this.checkboxHandler} />

I funkcja init it

{this.viewCheckbox({ key: 'yourKey', text: 'yourText', checked: this.state.yourKey })}
 4
Author: user2061097,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-11 18:46:43

Oto kod, który zrobiłem jakiś czas temu, może się przydać. musisz pobawić się tą linią => tą.state = { checked: false, checked2: true};

class Componente extends React.Component {
  constructor(props) {
    super(props);

    this.state = { checked: false, checked2: true};
    this.handleChange = this.handleChange.bind(this);
    this.handleChange2 = this.handleChange2.bind(this);

  }  

  handleChange() {
    this.setState({
        checked: !this.state.checked      
    })
  }

  handleChange2() {
    this.setState({
        checked2: !this.state.checked2      
    })
  }

  render() {
    const togglecheck1 = this.state.checked ? 'hidden-check1' : '';
    const togglecheck2 = this.state.checked2 ? 'hidden-check2' : '';

    return <div>
        <div>
        <label>Check 1</label>
        <input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
        <label>Check 2</label>
        <input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked2 } onChange={ this.handleChange2 } />
      </div>

      <div className={ togglecheck1 }>show hide div with check 1</div>
      <div className={ togglecheck2 }>show hide div with check 2</div>

    </div>;
  }
}

ReactDOM.render(
  <Componente />,
  document.getElementById('container')
);

CSS

.hidden-check1 {
  display: none;  
  }

.hidden-check2 {
  visibility: hidden;
}

HTML

  <div id="container">
      <!-- This element's contents will be replaced with your component. -->
  </div>

Oto kod = > http://codepen.io/parlop/pen/EKmaWM

 0
Author: Southpaw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-31 22:24:51
 <div className="form-group">
          <div className="checkbox">
            <label><input type="checkbox" value="" onChange={this.handleInputChange.bind(this)}  />Flagged</label>
            <br />
            <label><input type="checkbox" value=""  />Un Flagged</label>
          </div>
        </div

HandleInputChange (event) {

console.log("event",event.target.checked)   }

Powyższy uchwyt daje wartość true lub false po sprawdzeniu lub niezaznaczeniu

 -2
Author: user2903536,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-18 10:59:56

Ustawiam stan jako dowolny typ []. a w konstruktorze Ustaw stan na null.

onServiceChange = (e) => {
    const {value} = e.target;
    const index = this.state.services.indexOf(value);
    const services = this.state.services.filter(item => item !== value);
    this.setState(prevState => ({
        services: index === -1 ? prevState.services.push(value) && prevState.services : this.state.services.filter(item => item !== value)
    }))
}

W elemencie wejściowym

To.onServiceChange (e)} / > to.onServiceChange (e)} / > to.onServiceChange (e)} / > to.onServiceChange (e)} / >

Rozgryzłem to po jakimś czasie. Pomyślałem, że to wam pomoże:)

 -2
Author: Sachin R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-29 20:45:50