简体   繁体   English

确定是否检查了自定义无线电组件

[英]Work out whether custom radio component is checked or not

I have a custom radio component in React, when I check and uncheck the values it adds items to an object and should have true or false based on whether they are checked.我在 React 中有一个自定义无线电组件,当我检查和取消选中它的值时,它会将项目添加到 object 并且应该根据它们是否被检查为真或假。

At the moment it adds the true value correctly with the name of the radio but I can't seem to find out how to work to make the option false if another option is chosen.目前,它使用收音机的名称正确地添加了真值,但如果选择了另一个选项,我似乎无法找到如何使该选项为假。

I am currently using我目前正在使用

constructor() {
  super();
  this.state = {
    time_frame: {},
  }

  this.handleRadioChange = this.handleRadioChange.bind(this);
}

handleRadioChange(event) {
  let name = event.target.name
  let timeFrameCopy = this.state.time_frame;
  console.log(event.target)
  timeFrameCopy[event.target.value] = true
  this.setState({[name]: timeFrameCopy,}, this.checkState)
  return
  }
}

checkState(event) {
  console.log(this.state)
}

My radio component is我的无线电组件是

const Radio = (props) => {
  return (
    <Col>
      <div>
        <input id={props.value} type="radio" name={props.name} value={props.value} className="visually-hidden" onChange={props.handleChange}/>
        <label htmlFor={props.value} className="switch-label checkbox-label text-center">{props.label}</label>
      </div>
    </Col>
  )
}

export default Radio导出默认电台

If I check one radio button and then the other my state still has the data:如果我检查一个单选按钮,然后另一个我的 state 仍然有数据:

time_frame: {single: true, recurring: true}

Even though I would expect one of them to be false即使我希望其中一个是假的

If I understand correctly, you're trying to store in the state an object called time_frame , which is going to contain one pair of property-value per radio input, where the name of each of them would be the property name and the checked status the value.如果我理解正确,您正在尝试在 state 中存储一个名为time_frame的 object ,每个无线电输入将包含一对属性值,其中每个输入的名称将是属性名称和checked状态价值。 If that's the case, I see a logic problem.如果是这样的话,我看到一个逻辑问题。 since you're hard-coding true (for what I understand from your code) always instead of looking for the value stored and toggling/flipping it.因为你总是硬编码true (我从你的代码中理解)而不是寻找存储的值并切换/翻转它。

handleRadioChange() function should be something like: handleRadioChange() function 应该是这样的:

handleRadioChange(event) {
        let name = event.target.name;
        this.setState((currentState)=>{
        let timeFrameCopy = currentState.time_frame;
         timeFrameCopy[name] = event.target.checked;
          return { "time_frame": timeFrameCopy };
        });
}

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

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