reactjs - 如何将自定义 radio 组设置为 redux 形式

标签 reactjs redux redux-form

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

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"
  />

最佳答案

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

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

您应该会在自定义组件中看到 Prop 。

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

关于reactjs - 如何将自定义 radio 组设置为 redux 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55340339/

相关文章:

javascript - 如何让这个 React 方法返回语句/变量?

typescript - 如何使用 redux 4.0.1、redux-thunk 2.3.0 和 typescript 3.1.3 正确键入 redux-thunk actions 和 mapDispatchToProps

javascript - 在 redux 中获取 api 的最佳方式是什么?

javascript - redux-form + React-widgets DateTimePicker

reactjs - Redux 表单自定义选择不使用第一个值

javascript - React 和 websocket - 数据操作

reactjs - 如何隐藏react-data-grid中的列

reactjs - 使用 React : Property does not exist on type 'IntrinsicAttributes' 在 Typescript 中转译错误

reactjs - 使用 React 和 TypeScript 时如何正确输入 @connect?

reactjs - Redux Form 6.1.1 - 模糊验证不适用于 react native