首页 > 解决方案 > 单选按钮的反应组件

问题描述

我有一个包含许多输入和选择字段的表单。我使用输入和选择进行管理,但现在我正在尝试添加单选按钮和文本区域。在用户选择一个选项后,我发送的 json 没有更新来自无线电标头的值,并且选中的属性在按下时也没有更新。

这是单选按钮组件:

class RadioButton extends Component {
  state = {
    selectedOption: this.props.options[0].name,
  };

  handleOptionChange = (changeEvent) => {
    this.setState({
      selectedOption: changeEvent.target.value,
    });
  };

  render() {
    const { name, label, headline, options, ...rest } = this.props;
    return (
      <div>
        <legend>{headline}</legend>
        {options.map((option) => (
          <div className="form-check">
            <label className="form-check-label" htmlFor={name}>
              <input
                type="radio"
                className="form-check-input"
                name={name}
                key={option._id}
                value={option.value}
                checked={this.state.selectedOption === option.name}
                onChange={this.handleOptionChange}
              ></input>
              <label>{option.name}</label>
            </label>
          </div>
        ))}
      </div>
    );
  }
}

这是我在表单中呈现单选按钮的代码:

  renderRadioButton(name, label, headline, options) {
    const { data } = this.state;
    console.log(name);
    return (
      <RadioButton
        name={name}
        label={label}
        headline={headline}
        value={data[name]}
        options={options}
      />
    );
  }

这是渲染单选按钮的调用(此类派生表单类):

  state = {
    data: {
      first_name: "",
      last_name: "",
      is_looking_for_job: "",
    },
    boolean_options: [
      { _id: 1, name: "Yes", value: "True" },
      { _id: 2, name: "No", value: "False" },
    ],
  };
          {this.renderRadioButton(
            "is_looking_for_job",
            "Looking for job",
            "Looking for job",
            this.state.boolean_options
          )}

我希望有一个人可以帮助我。提前致谢!

标签: reactjs

解决方案


我认为这条线是问题所在:

checked={this.state.selectedOption === option.name}

将其更改为:

checked={this.state.selectedOption === option.value}

推荐阅读