我正在嘗試做位于抽屜組件上的自動對焦輸入組件。我從 Antd 獲取的所有組件。問題是自動對焦不能立即起作用,而只能在視窗打開和關閉后起作用。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;
uj5u.com熱心網友回復:
你可以試試這個。我測驗了它并且有效。
if (visible) {
setTimeout(() => {
inputRef.current.focus();
}, [500]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465477.html
標籤:javascript 反应 蚂蚁
下一篇:單擊拒絕/關閉后禁用兩個按鈕
