【问题标题】:How can I focus on next input when the first input value length is 3?当第一个输入值长度为 3 时,如何专注于下一个输入?
【发布时间】:2020-10-01 09:41:36
【问题描述】:

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

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

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

我想要实现的是当 name Field 中的值的长度为 3 时,名为 other 的 Field 获得焦点。

如何编写一个函数,名称字段值长度为 3,然后专注于其他字段?

【问题讨论】:

    标签: reactjs forms formik


    【解决方案1】:

    你需要得到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"/>}
    />
    

    【讨论】:

    • 更新了答案。看起来与Field 组件的任何交互都非常有限,您必须呈现自定义组件。我不确定other 字段是否需要这样的自定义,因为您可以使用一些innerRef 道具
    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多