以编程方式更改Redux-Form字段值

以编程方式更改Redux-Form字段值

问题描述:

当我使用 redux-form v7时,我发现没有办法设置字段值。现在我的表格,我有两个选择组件。当第一个选择组件值发生变化时,第二个值将清除。

When I use redux-form v7, I find there is no way to set the field value. Now in my form, I have two select component. The second's value will be clear when the first select component value changed.

在类渲染中:

<div className={classNames(style.line, style.largeLine)}>
  <div className={style.lable}>site:</div>
  <div className={style.content}>
    <Field
      name="site"
      options={sites}
      clearable={false}
      component={this.renderSelectField}
      validate={[required]}
    />
  </div>
</div>

<div className={classNames(style.line, style.largeLine)}>
  <div className={style.lable}>net:</div>
  <div className={style.content}>
    <Field
      name="net"
      options={nets}
      clearable={false}
      component={this.renderSelectField}
      validate={[required]}
      warning={warnings.net}
    />
  </div>
</div>

现在我添加选择更改挂钩,以及如何更改其他选择

Now I add the select change hook, and how can I change the other select value

renderSelectField = props => {
  const {
    input,
    type,
    meta: { touched, error },
    ...others
  } = props
  const { onChange } = input
  const _onChange = value => {
    onChange(value)
    this.handleSelectChange({ value, type: input.name })
  }
  return (
    <CHSelect 
      error={touched && error}
      {...input}
      {...others}
      onChange={_onChange}
      onBlur={null}
    />
  )
}


您可以在 this.handleSelectChange({value,type:input.name})中使用onChange逻辑并使用 更改来自redux-form的行动

You can have the onChange logic in this.handleSelectChange({ value, type: input.name }) and use change action from redux-form

根据文档:


更改(字段:字符串,值:任意):函数

更改
字段的值在Redux商店。这是一个绑定的动作创建者,因此
不返回任何内容。

Changes the value of a field in the Redux store. This is a bound action creator, so it returns nothing.

代码:

handleSelectChange = (value, type) => {
     if(type === "site") {
          this.props.change('net', "newValue");
     }
}
const mapDispatchToProps = (dispatch) => {
   return bindActionCreators({change}, dispatch);
}