我在使用 redux-form 进行登录表单字段验证时遇到问题。目前,我只是尝试让同步验证正常工作,以便检查基本错误。问题是表单似乎只在组件安装时检查验证,然后在该点之后不再检查验证。这是我的代码:
import React from 'react';
import { Field, reduxForm } from 'redux-form';
import * as Redux from 'react-redux';
import Input from './../../helpers/Input';
import Button from './../../helpers/Button';
export const Signup = React.createClass({
renderInput({ label, type, input: { value }, meta: { touched, error }}){
return (
<Input label={ label }
type={ type }
filled={ value ? true : false }
touched={ touched }
error={ error } />
);
},
render(){
const { handleSubmit } = this.props;
return(
<div>
<form onSubmit={ handleSubmit }>
<Field name="email" label="Email" component={ this.renderInput } />
<Field name="username" label="Username" component={ this.renderInput } />
<Field name="password" label="Password" type="password" component={ this.renderInput } />
<Field name="confirmPassword" label="Confirm Password" type="password" component={ this.renderInput } />
<Button type="submit" btnType="main" btnIcon="" btnText="Create Account" />
</form>
</div>
);
}
});
export const validate = values => {
const errors = {};
if (!values.username) {
errors.username = 'Required';
} else if (values.username.length > 15) {
errors.username = 'Must be 15 characters or less';
}
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
console.log(errors);
return errors;
};
export default reduxForm({
form: 'signup',
validate
})(Signup);
我感觉我在这里遗漏了一些非常基本的东西,但我很困惑。我觉得应该调度一个 Action 来切换“touched”属性 onBlur (从而重新渲染表单),但它似乎没有这样做,而且我在阅读 redux-form 文档时找不到类似的内容。有什么想法吗?
请您参考如下方法:
你没有通过onChange处理程序到您的 Input组件,因此 redux-form 不知道值已更改。
问题出在这里:
renderInput({ label, type, input: { value }, meta: { touched, error }}){
return (
<Input label={ label }
type={ type }
filled={ value ? true : false }
touched={ touched }
error={ error } />
);
},
要解决此问题,请传递 input作为您的 Input 的属性(property)组件并像这样定义它,例如:
<div className="input-row">
<input {...input} type="text"/>
{touched && error &&
<span className="error">{error}</span>}
</div>
不要忘记将函数签名更改为 renderInput({ label, type, input, meta: { touched, error }}) { ... } -value此处已删除。
作为替代方案,您可以显式传递 onChange :
renderInput({ label, type, input: { value, onChange }, meta: { touched, error }}){
return (
<Input label={ label }
onChange = { onChange }
type={ type }
filled={ value ? true : false }
touched={ touched }
error={ error } />
);
},
然后使用onChange在你的<Input ... />






