当第一个输入值的长度为3时,如何关注下一个输入?

时间:2020-06-11 16:58:28

标签: reactjs forms formik

我正在使用formik,我有2个输入字段。

const initialValues = {
  name: '',
  other: ''
};

<Formik initialValues={initialValues}>
  <Form>
    <Field name="name" />
    <Field name="other" />
  </Form>
</Formik>

我要实现的是,当名称字段中的值的长度为3时,名为other的字段将重点关注。

我该如何编写一个名称字段的值长度为3然后关注另一个字段的函数?

1 个答案:

答案 0 :(得分:2)

您需要获取other字段的引用

-编辑

I see Field doesn't have onChange prop, but there is component which allows you to render specific input and attach onChange handler there

虽然看起来糟透了

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"/>}
/>