简体   繁体   English

自动对焦输入组件 Antd

[英]Autofocus Input component Antd

I'm try to do autofocus Input component which is situated on Drawer component.我正在尝试执行位于抽屉组件上的自动对焦输入组件。 All componen i take from Antd.我从 Antd 获取的所有组件。 The problem is that the autofocus does not work immediately but only after the window opens and closes.问题是自动对焦不会立即起作用,而是在 window 打开和关闭后才起作用。 Link on CodeSandbox https://codesandbox.io/s/quizzical-morning-1nhi2v?file=/src/App.js CodeSandbox 上的链接https://codesandbox.io/s/quizzical-morning-1nhi2v?file=/src/App.js

import './App.css';
import 'antd/dist/antd.css';
import {Button, Drawer, Input} from 'antd'
import React, { useState, createContext, useRef, useEffect } from 'react';

function App() {

  const  inputRef = useRef(true);
  const [visible, setVisible] = useState(false);

  const onClose = () =>{ //Close Drawer 
    setVisible(false);
  } 
  const open = () =>{ //Open Drawer and must be autofocus on Input
    setVisible(true);
  }
  useEffect(()=>{
    console.log(visible + 'useEffect');
    if(visible){
      inputRef.current.focus();
    }
  }, [visible])

  return (
    <div className="App">
      <Drawer visible={visible} onClose={onClose} autoFocus={true}>
        <Input ref={inputRef} ></Input>     
      </Drawer>     
      <Input ref={inputRef_}  ></Input>
      <Button onClick={open}>  Open</Button>
    </div>
  );
}

export default App; 

You can try this.你可以试试这个。 I tested and it worked.我测试过并且有效。

if (visible) {
  setTimeout(() => {
    inputRef.current.focus();
  }, [500]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM