当第一个输入值长度为 3 时,如何关注下一个输入?
How can I focus on next input when the first input value length is 3?
我正在使用 formik,我有 2 个输入字段。
const initialValues = {
name: '',
other: ''
};
<Formik initialValues={initialValues}>
<Form>
<Field name="name" />
<Field name="other" />
</Form>
</Formik>
我想实现的是,当name Field 中的值的长度为3 时,other 命名的Field 获得焦点。
如何编写名称字段值长度为 3 的函数,然后专注于其他字段?
您需要获取 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"/>}
/>
我正在使用 formik,我有 2 个输入字段。
const initialValues = {
name: '',
other: ''
};
<Formik initialValues={initialValues}>
<Form>
<Field name="name" />
<Field name="other" />
</Form>
</Formik>
我想实现的是,当name Field 中的值的长度为3 时,other 命名的Field 获得焦点。
如何编写名称字段值长度为 3 的函数,然后专注于其他字段?
您需要获取 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"/>}
/>