React Hooks 进入页面以后自动 focus 到某个输入框
点击按钮focus到某个输入框
import React, { useRef, useEffect } from 'react'
export default function TextInputWithFocusButton() {
const inputEl = useRef(null)
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus()
}
useEffect(() => {
inputEl.current.focus()
}, [])
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
)
}