以 redux-form 显示 onChange 错误信息
Displaying error messages onChange in redux-form
我正在尝试使用 redux-form 字段(连同 Material-ui)和验证。当我离开该字段(即 onBlur)时,似乎会显示错误消息。我想要实现的是在用户键入时即时进行验证,并在 onChange 事件中显示错误消息。我将如何实现这种行为?
import { TextField } from 'redux-form-material-ui';
import { Field, reduxForm } from 'redux-form';
const MyForm = (props) => (
<form>
<div className="form-group">
<Field
name="foo"
type="text"
hintText="Foo"
component={TextField}
/>
</form>
);
export default reduxForm({
form: 'MyForm',
validate
})(MyForm);
验证的默认行为是仅在触摸字段时显示消息(即 onBlur)。
我想你可以通过在 componentWillMount 中使用 touch 方法来解决这个问题,这样它就会在挂载时被触及:
componentWillMount() {
const { touch } = this.props;
touch('foo');
}
然而,这确实有一个缺点,即可能会在加载表单时直接显示任何错误,但在这种情况下,会立即在 onChange 中触发验证。
你玩过CodeSandbox中的例子吗?正如丹尼斯建议的那样,您可以调用 "touch",但根据您的需要,您可以选择在更改时执行此操作:
<Field
name="username"
type="text"
component={renderField}
label="Username"
onChange={() => touch('username')}
/>
我正在尝试使用 redux-form 字段(连同 Material-ui)和验证。当我离开该字段(即 onBlur)时,似乎会显示错误消息。我想要实现的是在用户键入时即时进行验证,并在 onChange 事件中显示错误消息。我将如何实现这种行为?
import { TextField } from 'redux-form-material-ui';
import { Field, reduxForm } from 'redux-form';
const MyForm = (props) => (
<form>
<div className="form-group">
<Field
name="foo"
type="text"
hintText="Foo"
component={TextField}
/>
</form>
);
export default reduxForm({
form: 'MyForm',
validate
})(MyForm);
验证的默认行为是仅在触摸字段时显示消息(即 onBlur)。
我想你可以通过在 componentWillMount 中使用 touch 方法来解决这个问题,这样它就会在挂载时被触及:
componentWillMount() {
const { touch } = this.props;
touch('foo');
}
然而,这确实有一个缺点,即可能会在加载表单时直接显示任何错误,但在这种情况下,会立即在 onChange 中触发验证。
你玩过CodeSandbox中的例子吗?正如丹尼斯建议的那样,您可以调用 "touch",但根据您的需要,您可以选择在更改时执行此操作:
<Field
name="username"
type="text"
component={renderField}
label="Username"
onChange={() => touch('username')}
/>