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

Programmatically change Redux-Form Field value

当我使用redux-form v7 时,我发现无法设置字段值。现在在我的 form 中,我有两个 select 组件。当第一个 select 组件值更改时,第二个值将被清除。

在class渲染中:

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

现在我添加 select 更改挂钩,我如何更改其他 select

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 逻辑并使用 change action from redux-form

根据文档:

change(field:String, value:any) : Function

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

代码:

import { change } from "redux-form";

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

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({change}, dispatch);
}