首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReactJS:管理单选按钮行为

ReactJS:管理单选按钮行为
EN

Stack Overflow用户
提问于 2021-04-22 15:28:50
回答 1查看 27关注 0票数 0

我有一个表格,其中有两个单选按钮,其中一个是免费的,为付费。我应该设法回答这个问题。因此,如果用户点击:

代码语言:javascript
复制
Gratis: Yes --> Pay: No. 
Gratis: No ---> Pay: Yes
Pay: Yes ---> Gratis: No.
Pay: No ---> Gratis: Yes



if(Gratis == "true" && Pay !== undefined){
    questionnaire.SelfCertification.Pay = "false"
  }
  if(Gratis == "true" && Pay === undefined){
    Pay = "false"
  }
  if(Gratis == "false" && Pay !== undefined){
    Pay = "true"
  }
  if(Gratis == "false" && Pay === undefined){
    Pay = "true"
  }
  if(Pay == "true" && Gratis === undefined){
    Gratis = "false"
  }
  if(Pay == "false" && Gratis === undefined){
    Gratis = "true"
  }

我尝试过这样做,但有一些情况不能正常工作,例如:

如果我选择

代码语言:javascript
复制
Pay: Yes --> Gratis: No (and this is ok), 
//but if now i select 
Pay: No --> Gratis: No ( and it should go to Yes).

我该怎么做呢?

EN

回答 1

Stack Overflow用户

发布于 2021-04-22 16:19:58

您可以对这两个(或更多)无线电输入使用一个无线电组,并在它们之间切换。这里有一个非常简单的例子。

代码语言:javascript
复制
const [gratisPay, setGratisPay] = useState("Gratis");

const changeHandler = (e) => {
  // e.target.value is the radio input value
  // do what you need, like update some state
  setGratisPay(e.target.value);
};

...

<form onSubmit={submitHandler}>
  <label>
    Gratis
    <input
      type="radio"
      value="Gratis"
      name="gratisPay"
      checked={gratisPay === 'Gratis'}
      onChange={changeHandler}
      />
  </label>
  <label>
    Pay
    <input
      type="radio"
      value="Pay"
      name="gratisPay"
      checked={gratisPay === 'Pay'}
      onChange={changeHandler}
    />
  </label>
  <button type="submit">Submit</button>
</form>

提交表单只是记录单选项组的值。

演示

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67208668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档