【问题标题】:How to set custom radio group into redux form如何将自定义单选组设置为 redux 形式
【发布时间】:2019-03-25 14:41:14
【问题描述】:

我应该怎么做才能将 ColoredRadioGroup 设置为我的表单状态?从 redux-form 文档中尝试了一些东西,但没有帮助。我听说过传递 onChange 和 value 道具,但我不确定在我的情况下如何做。

ColoredRadioGroup.js:

class CustomRadioGroup extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      value: props.defaultValue,
    };
  }

  setValue = (value) => {
    this.setState(() => ({ value }));
  };

  handleChange = (event) => {
    if (this.props.onChange) {
      this.props.onChange(this.props.data.filter(elem => elem.value === event.target.value)[0]);
    }
    this.setState({ value: event.target.value });
  };

  render() {
    return (
      <RadioGroup
        style={this.props.groupStyle}
        name={this.props.groupName}
        value={this.state.value}
        onChange={this.handleChange}
      >
        <FormControlLabel
          value="green"
          control={
            <GreenRadio
              icon={<CheckBoxOutlineBlankIcon />}
              checkedIcon={<CheckBoxIcon />}
            />
          }
        />
        <FormControlLabel
          value="yellow"
          control={
            <YellowRadio
              icon={<CheckBoxOutlineBlankIcon />}
              checkedIcon={<CheckBoxIcon />}
            />
          }
        />
    ...
      </RadioGroup>
    );
  }
}

export default CustomRadioGroup;

在表单文件中:

  <Field
    component={props => <ColoredRadioGroup value={props.input.value} />}
    name="agent_group"
    type="radio"
  />

【问题讨论】:

    标签: reactjs redux redux-form


    【解决方案1】:

    当您将组件包装在 Field 中时 redux-form 将通过 props 传递输入和元对象。 以你的方式,你只是通过 props.input.value 道具。 您需要在 handleChange 中使用 props.input.onChange 来更新 redux 商店中的特定字段。 像这样重构它:

     <Field
      component={ColoredRadioGroup}
      name="agent_group"
    />
    

    您应该会在自定义组件中看到这些道具。

    查看https://redux-form.com/8.1.0/docs/api/field.md/#props 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2016-11-06
      • 2023-03-26
      • 2021-08-19
      相关资源
      最近更新 更多