问题
I'm trying to use radio buttons in React (that I always used) but this time with 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
any idea on how to get the value?
回答1:
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. Use 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
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>
);
};
Demo
来源:https://stackoverflow.com/questions/62551480/react-with-bootstrap-and-radio-buttons