如何在Formik表单的输入字段上设置自动聚焦?

问题描述 投票:0回答:4
reactjs formik
4个回答
5
投票

您可以简单地使用 TextInput 来执行此操作,就像我所做的那样 只需添加一个属性

<TextInput autoFocus={true} /> 

然后查看结果


1
投票

您可以将 useEffect 与 document.getElementByName 结合使用。这是方法;

使用空括号仅运行一次 useEffect:

  useEffect(() => {
    document.getElementsByName("name of your formik element")[0].focus();

    // following is optional
    return () => {
      formik.resetForm();
    }
  }, []);

0
投票

对于未来的人们:

我在这个问题中使用了 React 类组件。我设法通过添加处理焦点的方法解决了这个问题。通过 DOM 中的 ID 获取元素。

focusChange(nextField) {
 if(document.getElementById(nextField) === null){
   return;
 }
 document.getElementById(nextField).focus();

}

然后在类的渲染方法中我检查了一个关键事件。键码 13(输入)检查是为了防止提交表单。

const onKeyDown = (keyEvent) => {
     if ((keyEvent.charCode || keyEvent.keyCode) === 13) {
       this.focusChange(this.state.nextBarcode);
       keyEvent.preventDefault();
       keyEvent.keyCode = 9;
     }
   }

我将该方法添加到我的 Formik 表单中:

<Form onKeyDown={onKeyDown}>

来自 PrimeReact 的实际输入字段如下所示:

<InputText
      className="p-inputtext"
      id='barcode4'
      onChange={(e) => this.setState({barcode4: e.target.value, nextBarcode: 'barcode5'})}
      value={this.state.barcode4}
      style={{ width: 250 }} />

所以我的解决方案是

document.getElementById("myID").focus();


0
投票

要让 Formik Field 组件自动对焦,请将 autoFocus 属性添加到 Field 组件,如下所示:

<Field 
autoFocus={true}
type="text"
name="barcode1"  
/>
© www.soinside.com 2019 - 2024. All rights reserved.