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>
    </>
  )
}

 

posted @ 2021-06-10 18:59  徐同保  阅读(579)  评论(0编辑  收藏  举报