Rag*_*nar 5 javascript forms reactjs redux redux-form
想要验证我的输入并根据用户交互更改 CSS。
从所需的验证方法开始,我用 a 包装所有输入组件<Field>
并传递给validate
一个 func 数组。就required
目前而言。
但是对于我的所有字段,值保持不变touched: false
并且error: "Required"
. 如果我在输入中触摸或添加内容,这些值保持不变。
验证
export const required = value => (value ? undefined : 'Required')
Run Code Online (Sandbox Code Playgroud)
姓名输入
import React from 'react';
import { Field } from 'redux-form'
import InputItem from 'Components/InputsUtils/InputItem';
import { required } from 'Components/InputsUtils/Validation';
const NameInput = () => (
<Field
name={item.spec.inputName}
type={item.spec.type}
component={InputItem}
validate={[required]}
props={item}
/>
);
export default NameInput;
Run Code Online (Sandbox Code Playgroud)
输入项
import React from 'react';
const InputItem = ({ spec, meta: { touched, error } }) => {
const { type, placeholder } = spec;
return (
<input
className="input"
type={type}
placeholder={placeholder}
/>
);
};
export default InputItem;
Run Code Online (Sandbox Code Playgroud)
GG.*_*GG. 10
有两种解决方案可以解决“touched is always false”问题。
1)确保input.onBlur
在您的组件中调用
对于输入:
const { input } = this.props
<input {...input} />
Run Code Online (Sandbox Code Playgroud)
对于没有 native 的自定义表单元素onBlur
:
const { input: { value, onChange, onBlur } } = this.props
const className = 'checkbox' + (value ? ' checked' : '')
<div
className={className}
onClick={() => {
onChange(!value)
onBlur()
}}
/>
Run Code Online (Sandbox Code Playgroud)
2)声明你的表格 touchOnChange
const ReduxFormContainer = reduxForm({
form: 'myForm',
touchOnChange: true,
})(MyForm)
Run Code Online (Sandbox Code Playgroud)
小智 4
只要您使用扩展运算符将这些道具传递到您的输入中,它就redux-form
可以在您的元素中控制自己的道具。<input />
例如,你在哪里做const InputItem = ({ spec, meta: { touched, error } }) => ...
尝试破坏组件的输入:const InputItem = ({ input, spec, meta: { touched, error } }) => ...
如果您有<input ... />
,请尝试执行以下操作:
<input
{...input}
className="input"
type={type}
placeholder={placeholder}
/>
Run Code Online (Sandbox Code Playgroud)
redux-form 捕获任何onBlur
事件onChange
并使用其自己的方法来更改touched
状态。您只需要按照如上所示传递这些内容即可。
这些是您所需要的:https://redux-form.com/7.1.2/docs/api/field.md/#input-props
归档时间: |
|
查看次数: |
8057 次 |
最近记录: |