问题描述
我正在尝试动态显示复选框,该复选框将具有state中定义的起始值。我正在使用Material-UI来显示ui组件。 状态在组件安装中填充,看起来像这样:
tagState: {
All: true,Pizza: false,Breakfast: false,Chicken: false
}
我使用对象条目和forEach为处于这种状态的每个键创建一个复选框:
<FormControl component="fieldset" className={classes.formControl}>
<FormGroup>
{Object.entries(tagState).forEach((tag) =>
<FormControlLabel
control={<CheckBox checked={tag.value} onChange={handleChange} name={tag.key}/>}
label={tag.key}
/>
)}
</FormGroup>
</FormControl>
我没有任何错误,但也没有任何输出。我已经在forEach循环中使用console.log(tag)进行了检查,它按照需要显示了所有键值对。
谢谢
解决方法
您应该使用map,因为forEach会迭代,但什么也不返回。
<FormControl component="fieldset" className={classes.formControl}>
<FormGroup>
{Object.entries(tagState).map(([key,value]) =>
<FormControlLabel
control={<Checkbox checked={value} onChange={handleChange} name={key}/>}
label={key}
/>
)}
</FormGroup>
</FormControl>