[英]React with bootstrap and Radio buttons
I'm trying to use radio buttons in React (that I always used) but this time with react-bootstrap
.我正在尝试在 React 中使用单选按钮(我一直使用),但这次使用
react-bootstrap
。 I have two radio buttons and I want just one to be checked and get that value.我有两个单选按钮,我只想检查一个并获得该值。
import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
const StandAdd = () => {
const [item, setItem] = useState({
kindOfStand: ""
});
const { kindOfStand } = item;
const handleInputChange = event => {
event.preventDefault();
setItem({ ...item, [event.target.name]: event.target.value });
};
const handleSubmit = event => {
event.preventDefault();
alert(`${kindOfStand}`);
};
return (
<form onSubmit={handleSubmit}>
<Form.Group controlId="kindOfStand">
<Form.Check
type="radio"
aria-label="radio 1"
label="Design"
onChange={handleInputChange}
checked={kindOfStand === "design"}
// value="design" // <-- once enabled I can't select it
/>
<Form.Check
type="radio"
aria-label="radio 2"
label="Food"
onChange={handleInputChange}
checked={kindOfStand === "food"}
// value="food" // <-- once enabled I can't select it
/>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</form>
);
};
export default StandAdd;
Codesandbox link: https://codesandbox.io/s/react-bootstrap-radio-button-1d443 Codesandbox 链接: https://codesandbox.io/s/react-bootstrap-radio-button-1d443
any idea on how to get the value?关于如何获得价值的任何想法?
Give a value
attribute to the Form.Check
s and then get the value using e.target.value
once you click the radio btn like this.给
Form.Check
一个value
属性,然后像这样单击无线电 btn 后使用e.target.value
获取值。 Use e.persist();
使用
e.persist();
to avoid getting the following error:以避免出现以下错误:
This synthetic event is reused for performance reasons.
出于性能原因,此合成事件被重用。 If you're seeing this, you're accessing the method currentTarget on a released/nullified synthetic event
如果您看到此内容,则表示您正在访问已发布/无效合成事件的 currentTarget 方法
const StandAdd = () => {
const [item, setItem] = useState({ kindOfStand: "", another: "another" });
const { kindOfStand } = item;
const handleChange = e => {
e.persist();
console.log(e.target.value);
setItem(prevState => ({
...prevState,
kindOfStand: e.target.value
}));
};
const handleSubmit = e => {
e.preventDefault();
alert(`${kindOfStand}`);
};
return (
<form onSubmit={handleSubmit}>
<Form.Group controlId="kindOfStand">
<Form.Check
value="design"
type="radio"
aria-label="radio 1"
label="Design"
onChange={handleChange}
checked={kindOfStand === "design"}
/>
<Form.Check
value="food"
type="radio"
aria-label="radio 2"
label="Food"
onChange={handleChange}
checked={kindOfStand === "food"}
/>
</Form.Group>
<Button variant="primary" type="submit">
Submit
</Button>
</form>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.