- 您需要创建一个自定义
input
.
- 您需要拦截并更新 redux 的
input.onChange
功能。
- 可选的-如果你想其他形式的value观来影响这个值,然后利用reduxForm的
formSelector
用react-redux
的connect
的mapStateToProps
访问formProps在组件内this.props
(工作下面的例子已经包含了此功能)
组件/CustomInput.js
import React from "react";
const CustomInput = ({
// we'll intercept redux's "onChange" func, while leaving the other
// input props as is in "inputProps"
input: { onChange, ...inputProps },
// the "handleChange" func below is the parent func that will handle input changes
handleChange,
// "rest" contains any additional properties (className, placeholder, type ...etc)
...rest
}) => (
// we spread out the "inputProps" and the "rest" of the props, then we add
// an "onChange" event handler that returns the "event" and the
// input's "onChange" func to our "handleChange" parent func
<input {...inputProps} {...rest} onChange={e => handleChange(e, onChange)} />
);
export default CustomInput;
容器/Form.js
class ControlledFormValue extends PureComponent {
// this parent func will handle updates through the "event.target.value";
// the value can be changed/altered and then passed to the input's
// "onChange" func to update the field
handleChange = ({ target: { value } }, onChange) => {
// this will alter the value by adding a "-" after each input update
onChange(`${value}-`);
setTimeout(() => console.log(this.props.values), 500);
};
render() {
return (
<form onSubmit={this.props.handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field
className="uk-input"
name="firstName"
component={CustomInput}
type="text"
placeholder="First Name"
handleChange={this.handleChange}
/>
</div>
</div>
...etc
</form>
);
}
}
工作示例:https : //codesandbox.io/s/lx1r4yjwy7