使用样式的组件中的反应对react中的文本输入进行自动对焦
如何在页面加载上使用样式的组件进行React中的TextInput?
我确实使用了usefect
,但看来它没有在文本输入上自动对焦。我希望将电子邮件文本输入重点放在页面加载上。
function App() {
const emailInput = useRef(null);
useEffect(() => {
if (emailInput.current) {
emailInput.current.focus();
}
}, []);
return (
<div>
<Input type="text" placeholder="Name" />
<Input type="email" placeholder="Email" innerRef={emailInput} />
</div>
);
}
How do you make the TextInput in React using Styled Components to be autoFocus on page load?
I did using useEffect
but it seems it doesn't autoFocus on the TextInput. I wanted the email text input to be focus outlined on page load.
Codesandbox -> CODESANDBOX
function App() {
const emailInput = useRef(null);
useEffect(() => {
if (emailInput.current) {
emailInput.current.focus();
}
}, []);
return (
<div>
<Input type="text" placeholder="Name" />
<Input type="email" placeholder="Email" innerRef={emailInput} />
</div>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
按照
样式components
文档,在InnerRef
节,
InnerRef
被弃用为V4:在React 16之前,没有一个很好的方法将参考文献传递给父母(使用回调除外)。在react 16.3
forward> forward> forward> forward> forward>
与useref
honk稍后。样式的组件V4已开始使用该机制。因此,您可以直接使用
Ref
:在另一侧,如果目的仅用于聚焦,则如@andy所述,
autofocus
属性可能是一个更好的选择:React的
autocus
属性正在与上面的代码完全相同(focus
在安装上以编程方式元素)。请勿将其与HTML的自动对焦
属性混淆,该行为在浏览器之间不一致。As per
styled-components
documentation, ininnerRef
section, theinnerRef
is deprecated as of v4:Before React 16, there was no nice way to pass references up to the parent (except using callbacks). In React 16.3
createRef
andforwardRef
have been introduced for doing that, along withuseRef
hook later. Styled Components v4, has started to use that mechanism.Therefore, you may use
ref
directly:On the other side, if the intent is only for focusing, as stated by @Andy, the
autoFocus
property may be a better choice:The React's
autoFocus
attribute is doing exactly the same thing as the code above (focus
programmatically element on the mount). Do not confuse it with HTML'sautofocus
attribute, which behavior is inconsistent between browsers.