简体   繁体   中英

Programmatically change Redux-Form Field value

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.

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

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

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.

Code:

import { change } from "redux-form";

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM