如何在React Bootstrap中实现单选按钮选项垂直排列
解决React Bootstrap单选按钮垂直排列的问题
问题出在你给每个Form.Check添加的inline属性上——这个属性的作用就是让单选按钮横向并排显示,所以只要去掉它,单选按钮就会自动垂直排列了。
修改后的代码示例
<Form.Group as={Row} name="formDemoYears" controlId="formDemoYears" onChange={this.props.handleChangeAsInt} > <Form.Label column sm={5}> 1. How long have you worked for the organization? </Form.Label> <Col> {/* 去掉每个Form.Check的inline属性 */} <Form.Check type="radio" label="Less than one year" value="Less than one year" name="formDemoYears" id="formDemoYears-1" defaultChecked={this.props.formDemoYears === "Less than one year"} /> <Form.Check type="radio" label="One year to less than two years" value="One year to less than two years" name="formDemoYears" id="formDemoYears-2" defaultChecked={this.props.formDemoYears === "One year to less than two years"} /> <Form.Check type="radio" label="Two years to less than five years" value="Two years to less than five years" name="formDemoYears" id="formDemoYears-3" defaultChecked={this.props.formDemoYears === "Two years to less than five years"} /> <Form.Check type="radio" label="Five years to less than ten years" value="Five years to less than ten years" name="formDemoYears" id="formDemoYears-4" defaultChecked={this.props.formDemoYears === "Five years to less than ten years"} /> <Form.Check type="radio" label="Ten years or more" value="Ten years or more" name="formDemoYears" id="formDemoYears-5" defaultChecked={this.props.formDemoYears === "Ten years or more"} /> </Col> </Form.Group>
额外优化(可选)
如果希望每个选项的布局更整齐(比如按钮和文字对齐更统一),可以给每个Form.Check包裹一层Form.Group,或者利用Bootstrap的Grid系统让每个选项占满整行:
<Col> <Form.Group as={Row}> <Form.Check type="radio" label="Less than one year" value="Less than one year" name="formDemoYears" id="formDemoYears-1" defaultChecked={this.props.formDemoYears === "Less than one year"} /> </Form.Group> {/* 其他选项同理 */} </Col>
本质上就是inline属性控制了单选按钮的排列方向,去掉它就会恢复默认的垂直堆叠样式,你之前只是没注意到这个属性的作用而已~
内容的提问来源于stack exchange,提问作者Adam Norton
相关产品推荐
相关产品推荐

