【发布时间】:2020-07-10 12:15:11
【问题描述】:
当我尝试在 Reactjs 中同时使用两个复选框时出现错误。我收到了这个错误信息:
TypeError: Cannot read property 'has' of undefined
FormContainer.render
src/container/formcontainer.component.js:268
265 | <label className="form-check-label">
266 | <input
267 | type="checkbox"
> 268 | checked={this.state.departRelated.isExternal.has}
| ^ 269 | onChange={this.onChangeExternal}
270 | className="form-check-input"
271 | />
下面是我的申请:
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
newPost: {
title: "",
type: "",
depart: "",
selectedList: [],
description: ""
},
departRelated: {
isExternal: {
has: false,
name: "External"
},
isInternal: {
have: false,
name: "Internal"
}
};
onChangeExternal = () => {
this.setState(initialState => ({
departRelated: {
isExternal: {
has: !this.state.departRelated.isExternal.has
}
}
}));
};
onChangeInternal = () => {
this.setState(initialState => ({
departRelated: {
isInternal: {
have: !this.state.departRelated.isInternal.have
}
}
}));
};
return (
<div className="form-check">
<label className="form-check-label">
<input
type="checkbox"
checked={this.state.departRelated.isExternal.has}
onChange={this.onChangeExternal}
className="form-check-input"
/>
External
</label>
</div>
<div className="form-check">
<label className="form-check-label">
<input
type="checkbox"
checked={this.state.departRelated.isInternal.have}
onChange={this.onChangeInternal}
className="form-check-input"
/>
Internal
</label>
{/* <p>this box is {msg}.</p> */}
</div>
)
我这里只展示相关部分。我必须将has(have) 和name 都保留在departRelated 中,因为我想稍后将名称(使用has(have) value == true)存储在我的数据库中。 我评论外部部分,内部部分工作,反之亦然。但是,当我同时应用外部和内部部件时,它会失败。 谁知道为什么???
【问题讨论】:
-
在继续之前先检查属性。
标签: javascript reactjs checkbox