所以我创建了一个 radio 组件,并且运行了一个 onChange 函数,但是当另一个具有相同组名的 radio 取消选择该 radio 时,它不会触发,为什么?
这是我的 radio 组件代码
import { useState } from 'react';
const RadioButton = (props) => {
const [checked, setChecked] = useState((props.checked !== undefined) ? props.checked : false);
const handleChange = () => {
console.log('changed to: ' + checked);
(checked) ? props.onChecked() : props.onUnchecked();
setChecked(!checked);
}
return (
<input type="radio" className={'border-grey custom-checkbox ' + (checked ? 'checked' : 'unchecked')} name={props.groupName} onChange={handleChange}/>
)
}
export default RadioButton;
最佳答案
OnChange event handler for radio button (INPUT type="radio") doesn't work as one value 上讨论了类似的问题
解决此问题的方法是处理父元素上单选按钮的更改和状态。
如何完成此操作的示例:
const Parent = () => {
const [buttons, setButtons] = useState([0, 0, 0]);
const handleClick = (index) => {
setButtons((buttons) => {
alert(`prev radio ${buttons}`);
// You add a condition of deselecting here if you want
// if(buttons[index] === 1 ) return [0,0,0]
const newButtons = [0, 0, 0];
newButtons[index] = 1;
alert(`new radio ${newButtons}`);
return newButtons;
});
};
return (
<form>
{buttons.map((_, index) => (
<RadioButton
handleClick={handleClick}
key={index}
index={index}
checked={buttons[index]}
/>
))}
</form>
);
};
const RadioButton = ({ index, checked, handleClick }) => {
return (
<input
value={"" + index}
type="radio"
onChange={() => handleClick(index)}
checked={checked}
/>
);
};
如果您需要在单选按钮旁边添加一些标签或其他内容,您可以将它们包装在一起(将 RadioButton 组件替换为下面的组件)
const CustomInputWithOtherInfo = ({ index, checked, handleClick }) => {
const otherInfo = [
{
label:"label1",
title:"title1"
},
{
label:"label2",
title:"title2"
},
{
label:"label3",
title:"title3"
},
]
return (
<div>
<h4>{otherInfo[index].title}</h4>
<label>{otherInfo[index].label}</label>
<input
value={"" + index}
type="radio"
onChange={() => handleClick(index)}
checked={checked}
/>
</div>
);
};
在这里您可以找到沙盒上的演示
https://codesandbox.io/s/react-playground-forked-ik1lo0?file=/index.js:129-335
关于javascript - 当其他 radio 取消选择时,React Radio onChange 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71630365/