我有几个单选按钮,我想通过首先设置初始状态来创建动态状态,然后将状态连接到当前状态或将键替换为新值(如果已经将其替换)后的每次单击存在。
我自己尝试过,所以如果看起来不对,请原谅。
这是我要做的事的一个示例。
import React, { useState } from "react";
import { FormGroup, CustomInput } from "reactstrap";
import UniqueString from "unique-string";
function Ratings({ parentCheckedGood, parentCheckedNA, Question }) {
//initializing empty state object
const [state, setState] = useState({});
//Here is where I am stuck, with each click after the first I should concatenate or
//replace
const handleChange = (e) => {
const { name, value } = e.target;
if (name in state) {
setState(...state, { name: value });
} else {
setState(...state, {
name: value,
});
}
};
console.log(state);
const string = UniqueString();
return (
<div>
<FormGroup required>
<div onChange={handleChange}>
<CustomInput
// checked={parentCheckedGood}
type="radio"
id={string + "1"}
name={Question}
value="Good"
label="Good"
/>
<CustomInput
type="radio"
id={string + "2"}
name={Question}
value="Fair"
label="Fair"
/>
<CustomInput
type="radio"
id={string + "3"}
name={Question}
value="Poor"
label="Poor"
/>
<CustomInput
// checked={parentCheckedNA}
name={Question}
type="radio"
id={string + "4"}
value="N/A"
label="N/A"
/>
</div>
</FormGroup>
</div>
);
}
export default Ratings;
这些单选按钮使我为自己的钱而奔波。 干杯
答案 0 :(得分:2)
使用setState
的函数格式,您在语法上已经接近:
const handleChange = (e) => {
const { name, value } = e.target;
setState(state => ({ ...state, [name]: value }))
};