简体   繁体   English

React 组件上的单选按钮需要额外点击才能被标记

[英]Radio buttons on a React component take an extra click to be marked

I have a very simple react functional component, with a div with some inputs of type radio.我有一个非常简单的反应功能组件,带有一个带有一些无线电类型输入的 div。 Just like this:像这样:

const radioHandler = (event) => {
   event.preventDefault();
   console.log(event.target.value);
}

return(
   <div className="radioDiv" onChange={radioHandler}>
      <label>My label:</label>
      <input type="radio" value="1" name="group_x" checked/> One
      <input type="radio" value="2" name="group_x"/> Two
      <input type="radio" value="3" name="group_x"/> Three
   </div>
);

Looks very simple, like this:看起来很简单,像这样: 它看起来如何

What happens is, the option number 1 is checked by default, as desired.发生的情况是,默认情况下会根据需要检查选项编号 1。 But when I click the others, it takes an extra click to actually change to the one I'm trying to check.但是当我点击其他人时,需要额外点击一下才能真正更改为我要检查的那个。 I've added an ´´´preventDefault()´´´ method because without it, I would click option 2, and then option 3, and it would jump to the default checked one, and not the 3. But with the preventDefault it takes an extra click to make the blue dot actually go to the desired option.我添加了一个 ´´´preventDefault()´´´ 方法,因为没有它,我会单击选项 2,然后单击选项 3,它会跳转到默认选中的选项,而不是 3。但是使用preventDefault它需要额外单击以使蓝点实际上是 go 到所需的选项。 Why is this?为什么是这样? How can I make it work properly?我怎样才能让它正常工作?

Hope this helps: basically remove the preventDefault behaviour and defaultChecked instead of checked.希望这会有所帮助:基本上删除 preventDefault 行为和 defaultChecked 而不是检查。

import "./styles.css";

export default function App() {
  const radioHandler = (event) => {
    console.log(event.target.value);
  };

  return (
    <div className="radioDiv" onChange={radioHandler}>
      <label>My label:</label>
      <input type="radio" value="1" name="group_x" defaultChecked /> One
      <input type="radio" value="2" name="group_x" /> Two
      <input type="radio" value="3" name="group_x" /> Three
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM