单选按钮需要点击两次才能使用React Hooks更改第二次



当我第一次点击任何单选输入时(意味着我只需要点击一次(。当我点击第二个无线电输入时,我必须做两次才能更改它。我该如何修复它?

export default function RadioInput() {
const { register, setValue } = useForm<FormData>();
const [inputValue1, setInputValue1] = useState('');
const [inputValue2, setInputValue2] = useState('');
const [isSelected1, setIsSelected1] = useState(false);
const [isSelected2, setIsSelected2] = useState (false);
const onChange1 = () => {
console.log(inputValue1)
setInputValue1(inputValue1)
setIsSelected1(!isSelected1)
};
const onChange2 = () => {
console.log(inputValue2)
setInputValue2(inputValue2)
setIsSelected2(!isSelected2)
};
const styles = {
radioPink: {
border: "10px solid green"
}
}
return (
<div>
<label className="radio">Company
<input type="radio" checked={isSelected1} value={inputValue1} onChange=. 
{onChange1} name="is_company"/>
<span className="checkround"/>
</label>
<label className="radio">Company
<input type="radio" checked={isSelected2} value={inputValue2} onChange= 
{onChange2} name="is_company"/>
<span className="checkround"/>
</label>
<button className="btn cust-btn " type="button" id="btn-registration"
>Register
</button>
</div>
);
}

由于这是一个单选控件,因此只能有一个选定选项。因此,它只需要一个国家。按照目前的情况,您可能会将两个单选选项都设置为true!让我们重构这个输入组,使其只有一个状态控件。

export default function RadioInput() {
const { register, setValue } = useForm<FormData>();
const [inputValue1, setInputValue1] = useState('');
const [inputValue2, setInputValue2] = useState('');
const [selected, setSelected] = useState();
const onChange1 = () => {
console.log(inputValue1)
setInputValue1(inputValue1)
setSelected(1)
};
const onChange2 = () => {
console.log(inputValue2)
setInputValue2(inputValue2)
setSelected(2)
};
const styles = {
radioPink: {
border: "10px solid green"
}
}
return (
<div>
<label className="radio">Company
<input type="radio" checked={selected === 1} value={inputValue1} onChange={onChange1} name="is_company"/>
<span className="checkround"/>
</label>
<label className="radio">Company
<input type="radio" checked={selected === 2} value={inputValue2} onChange={onChange2} name="is_company"/>
<span className="checkround"/>
</label>
<button className="btn cust-btn " type="button" id="btn-registration"
>Register
</button>
</div>
);
}

相关内容

  • 没有找到相关文章

最新更新