首页 > 解决方案 > 元素停止移动后如何将焦点设置为输入?

问题描述

在 React 中有一个搜索栏,在我单击“打开”按钮后会出现。因为我使用 translateX 属性,所以搜索栏看起来很流畅。然后我想在这个搜索栏中的输入元素上使用 focus() 。我尝试使用参考。焦点出现了,但只要我按下按钮,它就会出现,并一直保持搜索栏从屏幕的一个部分移动到另一个部分(记住,这是因为我使用 translateX)。所以这一切都在我眼前。屏幕上的搜索栏“到达目的地”后如何使焦点出现?我试过

  if (props.visibleSearchBar) {
    ReactDOM.findDOMNode(inputRef.current).focus()
  } 

代替

 if (props.visibleSearchBar) {
      inputRef.current.focus();
  } // same story


 const Search = (props) => {
     let inputRef = useRef(null);       
     if (props.visibleSearchBar) {
          inputRef.current.focus();
       }

     return (
       <div>
        <input ref={inputRef} />   
       </div >
     )

标签: reactjsfocus

解决方案


您可以最初禁用输入,并在转换结束后启用它。

像这样的东西,(它没有经过测试)。

const [disabled, setDisabledState] = useState(true)

useEffect(() => {
const callback = () => {
 setDisableState(false)
 inputRef.current.focus();
}
inputRef.current.addEventListener('transitionend', callback)

return () => inputRef.current.removeEventListener('transitioned', callback)
}, [])


 return (
       <div>
        <input ref={inputRef}  disabled={disabled}/>   
       </div >
     )

推荐阅读