Answer the question
In order to leave comments, you need to log in
How to make initial state of checkbox?
this.props.checked stores the initial state of the checkbox. But at the time of rendering, it is still empty, in render ( ) you cannot write state, Tell me what the thread is. Code below
export default class Checkbox extends Component {
constructor(props) {
super(props);
this.state = {
checked: this.props.checked
}
this.onChange = this.onChange.bind(this);
}
onChange(event) {
let checked = event.target.checked;
if( this.props.func )
this.props.func(checked);
this.setState({checked});
}
render() {
const { name, children } = this.props;
return(
<label className="checkbox">
<input name={name} type="checkbox" className="checkbox__input" onChange={this.onChange} checked={this.state.checked} />
<span className="checkbox__text">{children}</span>
</label>
)
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question