javascript - 当其他 radio 取消选择时,React Radio onChange 不起作用

标签 javascript html reactjs

所以我创建了一个 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/

相关文章:

javascript - 将修饰符类应用于数组中的指定元素[React]

javascript - 如何让javascript在浏览器上解析json.gz文件

javascript - 在 React 中推送数组返回空

php - 过滤这些输入的条件语句是什么?

javascript - 未捕获的类型错误无法读取未定义的属性 'body'

reactjs - 错误: Type '{ children: Element[]; }' has no properties in common with type 'IntrinsicAttributes & RefAttributes<HTMLFormElement>'

javascript - 使用值数组创建对象数组

javascript - ExtJS 6 - 存储 $binding 未定义

Javascript 只在字段中生成 1 个字符

javascript - 在 React Native 中是否有用于切换/显示 Inspector 的键盘快捷键?