React Checkbox not sending onChange -
tldr: utilize defaultchecked instead of checked, working jsbin here http://jsbin.com/mecimayawe/1/edit?js,output
trying setup simple checkbox cross out label text when checked. reason handlechange not getting fired when utilize component. can explain i'm doing wrong?
class="lang-js prettyprint-override">var crossoutcheckbox = react.createclass({ getinitialstate: function () { homecoming { complete: (!!this.props.complete) || false }; }, handlechange: function(){ console.log('handlechange', this.refs.complete.checked); // never gets logged this.setstate({ complete: this.refs.complete.checked }); }, render: function(){ var labelstyle={ 'text-decoration': this.state.complete?'line-through':'' }; homecoming ( <span> <label style={labelstyle}> <input type="checkbox" checked={this.state.complete} ref="complete" onchange={this.handlechange} /> {this.props.text} </label> </span> ); } });
usage:
class="lang-js prettyprint-override">react.rendercomponent(crossoutcheckbox({text: "text text", complete: false}), mountnode);
solution:
using checked doesn't allow underlying value alter (apparently) , doesn't phone call onchange handler. switching defaultchecked seems prepare this:
class="lang-js prettyprint-override">var crossoutcheckbox = react.createclass({ getinitialstate: function () { homecoming { complete: (!!this.props.complete) || false }; }, handlechange: function(){ this.setstate({ complete: !this.state.complete }); }, render: function(){ var labelstyle={ 'text-decoration': this.state.complete?'line-through':'' }; homecoming ( <span> <label style={labelstyle}> <input type="checkbox" defaultchecked={this.state.complete} ref="complete" onchange={this.handlechange} /> {this.props.text} </label> </span> ); } });
to checked state of checkbox path be:
this.refs.complete.state.checked
the alternative event passed handlechange
method:
event.target.checked
checkbox onchange reactjs
No comments:
Post a Comment