警告信息:
Warning: Received the string `true` for the boolean attribute `checked`. Although this works, it will not work as expected if you pass the string "false". Did you mean checked={true}?
in input (at Form.js:40)
in label (at Form.js:39)
完整代码如下:
import React from "react";
class Form extends React.Component{
state={
hobby:{
football:false,
basketball:false,
baseball:false
}
}
onChange=(e)=>{
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
hobby: { ...this.state.hobby, [name]:value }
});
// this.setState({
// hobby: { ...this.state.hobby, [e.target.name]: e.target.value }
// });
}
onSubmit=(e)=>{
e.preventDefault()
console.log(this.state.hobby)
}
render(){
const {football,basketball,baseball}=this.state.hobby
return(
<form onSubmit={this.onSubmit}>
<div className="checkbox">
爱好:
<label>
<input type="checkbox" name="football" value="true" checked={football} onChange={this.onChange}/> 喜欢足球
</label>
<label>
<input type="checkbox" name="basketball" value="true" checked={basketball} onChange={this.onChange}/> 喜欢篮球
</label>
<label>
<input type="checkbox" name="baseball" value="true" checked={baseball} onChange={this.onChange}/> 喜欢棒球
</label>
</div>
<div>
<button type="submit">提交</button>
</div>
</form>
);
}
}
export default Form
checkbox如果值为布尔类型,写法稍微有点儿区别 const value = target.type === 'checkbox' ? target.checked : target.value;