【问题标题】:Programmatically change Redux-Form Field value以编程方式更改 Redux-Form 字段值
【发布时间】:2017-12-27 02:01:56
【问题描述】:

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

在课堂上渲染:

<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}
    />
  )
}

【问题讨论】:

    标签: javascript reactjs redux redux-form


    【解决方案1】:

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

    根据文档:

    change(field:String, value:any):函数

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

    代码:

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

    【讨论】:

    • 是否有API可以同时设置多个字段?不在初始值期间
    • 这对于&lt;Field&gt; 组件的component='select' 变体如何工作?
    • @Dane 类似于它对输入字段的工作方式,它需要字段名称作为第一个参数以及您需要选择的选项值
    • import { change } from "redux-form";
    • 如果从redux-form导入change,则参数为:change(form: string, field: string, value: any, touch?: boolean, persistentSubmitErrors?: boolean): FormAction
    猜你喜欢
    • 2019-03-11
    • 2022-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多