首页 > 解决方案 > redux 表单字段的单选按钮

问题描述

它不能正常工作,我只想选择一个值,但我可以选择一个和多个......并且无法取消选择

该功能有代码。

const RadioButtonField = ({type, options, disabled, onChange}) => {

   const handleChange = (value) => {
        onChange(type, value);
    };

    return (
        <div>
            {options.map(({ value, label }) =>
                <Radio.Group key={value}>
                    <Radio
                        disabled={disabled}
                        onChange={() => handleChange(value)}
                    >
                        {label}
                    </Radio>
                </Radio.Group>
            )}
        </div>
    );
};

标签: reactjsformsreduxradio-buttonantd

解决方案


您可以参考以下代码:

class App extends React.Component {
  state = {
    initialValue: "A",
    options: ["A", "B", "C", "D"]
  };

  onChange = e => {
    console.log("radio checked", e.target.value);
    this.setState({
      value: e.target.value
    });
  };

  render() {
    return (
      <Radio.Group value={this.state.initialValue}>
        {this.state.options.map((value, index) => {
          return (
            <Radio onChange={this.onChange} key={index} value={value}>
              {" "}
              {value}{" "}
            </Radio>
          );
        })}
      </Radio.Group>
    );
  }
}

工作代码和框演示

我认为您不需要向该函数传递任何内容。每当单击该选项时,该event (e)对象将被传递给onChange(e)您,您将分别获得单击项的值和检查onChange(e) e.target.valuee.target.checked


推荐阅读