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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45230531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:58:05  来源:igfitidea点击:

Programmatically change Redux-Form Field value

javascriptreactjsreduxredux-form

提问by taven

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

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

In class render:

在类渲染中:

<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 selectchange hook, and how can I change the other selectvalue

现在我添加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}
    />
  )
}

回答by Shubham Khatri

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

您可以在redux-form 中this.handleSelectChange({ value, type: input.name })使用onChange 逻辑并使用change操作

According to the docs:

根据文档:

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.

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

更改 Redux 存储中字段的值。这是一个绑定动作创建者,所以它什么都不返回。

Code:

代码:

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