reactjs - 元素停止移动后如何将焦点设置为输入?
问题描述
在 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 >
)
解决方案
您可以最初禁用输入,并在转换结束后启用它。
像这样的东西,(它没有经过测试)。
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 >
)
推荐阅读
- scala - 是否可以在不评估的情况下对按名称参数进行模式匹配?
- flutter - 像 Flutter 中的标题文本一样收缩 SliverAppBar 图像动画
- angular - 使用 AngularFire 显示 Facebook 头像的正确方法是什么
- python - How to make a voice assistant in python that always listen for inputs?
- authentication - 问:如何在 IIS 应用程序中删除登录
- drupal - Drupal 本地开发设置/环境
- python - 使用 pandas 保存到 .csv 时,数字会发生变化
- javascript - 如何在复合组件中使用 useContext()?
- google-apps-script - 列表更改时自动添加/删除复选框(Google App Script)
- python - 具有基类模式的列表的棉花糖嵌套序列化以尊重子类模式类