我正在使用formik,我有2个输入字段。
const initialValues = {
name: '',
other: ''
};
<Formik initialValues={initialValues}>
<Form>
<Field name="name" />
<Field name="other" />
</Form>
</Formik>
我要实现的是,当名称字段中的值的长度为3时,名为other的字段将重点关注。
我该如何编写一个名称字段的值长度为3然后关注另一个字段的函数?
答案 0 :(得分:2)
您需要获取other
字段的引用
-编辑
虽然看起来糟透了
const otherRef = useRef(null);
// or this.otherRef = React.createRef(null)
const onChange = ({target: {value}}) => {
if(value.length > 3) {
otherRef.current.focus() // ideally you'd check before if otherRef is defined
}
}
<Field onChange={onChange} name="name"
component={({field: {onChange: onFormikChange, ...rest}, form, ...props}) =>
<input {...rest} {...props} onChange={(event) => {onFormikChange(event);onChange(event)}} type="text"/>}
/>
<Field name="other"
component={({field: {onChange: onFormikChange, ...rest}, form, ...props}) =>
<input {...rest} {...props} ref={otherRef} onChange={(event) => {onFormikChange(event);onChange(event)}} type="text"/>}
/>