Nat*_*all 10 forms reactjs redux redux-form
我在登录表单字段验证中使用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);Run Code Online (Sandbox Code Playgroud)
我觉得我在这里缺少一些非常基本的东西,但我很难过.我觉得应该派遣一个动作来切换布尔的"触摸"属性(从而重新渲染表单),但它似乎没有这样做,我找不到任何类似的读取通过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 } />
);
},
Run Code Online (Sandbox Code Playgroud)
要解决此问题,请将input作为属性传递给您的Input组件并按如下方式定义它:
<div className="input-row">
<input {...input} type="text"/>
{touched && error &&
<span className="error">{error}</span>}
</div>
Run Code Online (Sandbox Code Playgroud)
不要忘记将函数签名更改为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 } />
);
},
Run Code Online (Sandbox Code Playgroud)
然后onChange在你的中使用<Input ... />
| 归档时间: |
|
| 查看次数: |
3833 次 |
| 最近记录: |