问题
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}
/>
)
}
回答1:
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:
handleSelectChange = (value, type) => {
if(type === "site") {
this.props.change('net', "newValue");
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({change}, dispatch);
}
来源:https://stackoverflow.com/questions/45230531/programmatically-change-redux-form-field-value