mercredi 3 août 2016

ReactJS MaterialUI Checkboxes- setting state within onCheck()

Using material-ui 0.15.3 and react 15.3.0.

I have a Checkbox component and want to use this.setState within its onCheck function.

It became apparent pretty quickly that I had to manually pass something into the Checkbox's checked prop. If I don't, then I cannot use setState. If I try to do so, then the visual component of the checkbox wont update. E.g. I click the checkbox and it stays empty. My first question is why? Why can't I keep this as an uncontrolled component? Why must I pass something into the checked prop?

    <Checkbox
    label="1"
    style={styles.checkbox}
    onCheck={this.handleCheck.bind(this)}
    checked={this.state.box1} // if this is not supplied then I cannot use setState within handleCheck()

handleCheck():

  handleCheck(event, checked) {
    this.setState({
        box1: checked 
        someState: someValue 
    });
 }

Now I have multiple checkboxes, so my second question is, how can I structure this so it is as clean as possible? Will I need to have a separate state variable for each checkbox with individual handleCheck() functions? I feel like that would get messy very quickly. e.g. (state for box1, box2, box3 etc.)




Aucun commentaire:

Enregistrer un commentaire