[英]How can I make a React-Bootstrap radio group required with HTML validation?
I'm using a pair of React-Bootstrap radio buttons in my app.我在我的应用程序中使用了一对React-Bootstrap 单选按钮。 I need to require that the user make a selection.
我需要要求用户做出选择。 However, adding
required
as seen here doesn't have the same effect that it would on an HTML radio input.但是,如此处所示添加
required
不会产生与 HTML 无线电输入相同的效果。
<Form.Check inline label="One" type='radio' required />
<Form.Check inline label="Two" type='radio' required />
How can I apply the HTML5 required
attribute here?如何在此处应用 HTML5
required
属性? I'm looking for basic HTML5 validation, not React validation.我正在寻找基本的 HTML5 验证,而不是 React 验证。
Had the same issue as you, it's actually very simple and it's a shame they don't specify in the documentation.和你有同样的问题,它实际上很简单,很遗憾他们没有在文档中指定。
Give them all the same name.给他们都起一个名字。
<Form.Check name="grouped" required inline label="One" type='radio' />
<Form.Check name="grouped" required inline label="Two" type='radio' />
Step 1: Set flag in state, default to true
步骤 1:在 state 中设置标志,默认为
true
class HaveAccount extends Component {
state = {
flag: true,
};
render() {
const { haveAccount, updateHaveAccount } = this.props;
const handleChange = (e) => {
if (this.state.flag)
this.setState((prevState) => ({ ...prevState, flag: false }));
updateHaveAccount({ value: e.target.value });
};
return (
<div>
<Form className="d-flex flex-column justify-content-center">
<Form.Group as={Row}>
<Col sm={{ span: 7, offset: 5 }}>
<Form.Check
type="radio"
label="YES"
name="haveAccountRadios"
value={true}
id="haveAccountRadios1"
onChange={handleChange}
/>
<Form.Check
type="radio"
label="NOPE"
name="haveAccountRadios"
value={false}
id="haveAccountRadios2"
onChange={handleChange}
/>
</Col>
</Form.Group>
<Form.Group className="d-flex justify-content-center">
<Link
className={`button button-link ${
this.state.flag ? "disabled" : ""
}`}
to="/login"
>
Next
</Link>
</Form.Group>
</Form>
</div>
);
}
}
Step 2: I'm conditionally adding className disabled
based on the flag.第 2 步:我根据标志有条件地添加 className
disabled
。 Flag only gets updated first time handleChange
executes.标志仅在第一次执行
handleChange
时更新。
Step 3: Add CSS第 3 步:添加 CSS
.disabled {
background-color: #ccc;
pointer-events: none;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.