In a UI library I have a Checkbox class, which allows the user to add a input[type=checkbox] to a form, styles it and adds extra functionality:
export class Checkbox extends React.Component({
render() {
return(
<div className="form-component">
<input type="checkbox"
defaultChecked={this.props.value}
checked={this.props.value}
name={this.props.name} />
<label>{this.props.label}</label>
</div>
)
}
});
The change handler is done at the form level.
export class Page extends React.Component({
handleChange(event) {
let state = {};
state[event.target.name] = event.target.value;
this.setState(state);
}
render() {
<form onChange={this.handleChange}>
<Input value={this.state.value} name="input1" />
<Checkbox value={this.state.value} name="checkbox1" />
</form>
}
})
The synthetic change event from the input returns an event object with event.target.name
and event.target.value
. The checkbox has event.target.checked
instead. In the handle change event I can see what type of element it is choose accordingly.
But is there a way for me to overwrite the event being emitted from the Checkbox component, so that event.target.value === event.target.checked
?
You can change the value of CheckBox
on it's onChange
event. Because the event in CheckBox
will be called before the onChange
event, so you can format e.target
to return what you want. Try this:
var CheckBox = React.createClass({
handleChange: function(e){
e.target.value = e.target.checked
},
render: function(){
return (
<div className="form-component">
<input type="checkbox"
defaultChecked={this.props.value}
checked={this.props.value}
name={this.props.name}
onChange={this.handleChange}
/>
<label>{this.props.label}</label>
</div>
)
}
});
But be careful, e.target.value just changes into a String "false"
and "true"
, not Boolean
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.