[英]React - Show/Hide multiple divs from different check boxes
我是 React 新手,我在 JS 中有一定的领域,我想这是一个简单的问题,但我已经搜索了 2 个小时,但没有找到满意的答案:(
我有复选框:
<Col md="4">
<FormGroup>
<Label>Have Children</Label>
<CustomInput type="radio" name="customRadio" label="Yes" value="yes" />
<CustomInput type="radio" name="customRadio" label="No" value="no" />
</FormGroup>
</Col>
<Col md="4">
<FormGroup>
<Label>Have Spouse</Label>
...(same as children input)
</FormGroup>
</Col>
<Col md="4">
<FormGroup>
<Label>Have Family Members</Label>
...(same as children input)
</FormGroup>
</Col>
如果您单击“有孩子”,我希望显示一些与孩子相关的 div。 如果没有,它们应该被隐藏。 其他选项也是如此。
我想知道什么是最干净的方法来做到这一点。
复选框应该在状态中切换一个布尔值。
然后,如果 state 中的值为 true,则有条件地呈现子项。
因此,将选中的值和更改处理程序附加到您的组:
<FormGroup>
<Label>Have Children</Label>
<CustomInput type="radio" name="customRadio" label="Yes" value="yes" onChange={() => this.handleChange} checked={this.state.visibility} />
<CustomInput type="radio" name="customRadio" label="No" value="no" onChange={() => this.handleChange} checked={!this.state.visibility}/>
</FormGroup>
在您的类中创建状态值并使用 handleChange 方法切换它
state = {visibility: false}
handleChange = () => this.setState({visibility: !this.state.visibility})
然后你可以根据可见性布尔值有条件地渲染你的东西,所以......
<div>{this.state.visibility && <p>Now You see me</p>}</div>
只需事先考虑数据结构。
从你的问题来看,我假设你只是想要这样的东西:
children
复选框被选中,显示与children
相关的元素spouse
复选框被选中,显示与spouse
相关的元素。在我看来,您需要一组带有每个状态(选中或未选中)的复选框。 您可以将此信息存储在组件状态中。
// in the constructor
this.state = {
checkboxes: [
{ id: 1, label: 'children', checked: false },
{ id: 2, label: 'spouse', checked: false },
],
}
然后,在你的render()
函数中,你只需要像这样循环遍历数组:
const { checkboxes } = this.state;
return (
<div>
{checkboxes.map((checkbox, index) => (
<div>
<label>{checkbox.label}</label>
<input type="checkbox" checked={checkbox.checked} onClick={() => this.toggleCheckBox(index)} />
{checkbox.checked && <div>show this if the checkbox is checked</div>}
</div>
))}
</div>
);
只记得在类中实现this.toggleCheckBox
方法。 如果您不确定如何操作,这里有一个代码和框供您查看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.