React userref 未将焦点状态添加到字段

我一直在尝试为此找到解决方案,我想将焦点状态添加到我的输入字段中。但它似乎不起作用:


const textareaRef = useRef<HTMLInputElement>(null);

...


const handleClick = () => {

        if (textareaRef.current) {

            alert('Field clicked');

            textareaRef.current.focus();

            textareaRef.current.click();

        }

    };


...


<input

     ref={textareaRef}

     onClick={handleClick}

     onFocus={(e) => e.persist()}

     spellCheck="false"

/>


这是不行的,主要原因是要显示手机键盘。

叮当猫咪
浏览 101回答 2
2回答

蓝山帝景

我无法在桌面浏览器上重现该错误。录屏时用的是什么浏览器?function App() {&nbsp; const textareaRef = React.useRef();&nbsp; const handleClick = () => {&nbsp; &nbsp; if (textareaRef.current) {&nbsp; &nbsp; &nbsp; &nbsp; console.log('Field clicked');&nbsp; &nbsp; &nbsp; &nbsp; textareaRef.current.focus();&nbsp; &nbsp; }&nbsp; };&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <div onClick={handleClick}>click me to focus input</div>&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp;ref={textareaRef}&nbsp; &nbsp; &nbsp; &nbsp;onFocus={(e) => e.persist()}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; </div>&nbsp; )}ReactDOM.render(&nbsp; <App />,&nbsp; document.getElementById('root'))<script src="https://unpkg.com/react@16.14.0/umd/react.production.min.js"></script><script src="https://unpkg.com/react-dom@16.14.0/umd/react-dom.production.min.js"></script><div id="root"></div>

慕哥6287543

您可以在useEffect() Hook 中执行此操作。下面的组件模拟了您的场景。当组件加载时,我使 focus() 出现在输入上。import React, { useEffect, useRef } from 'react';const UseRefBasics = () => {&nbsp; const refContainer = useRef(null);&nbsp; const handleSubmit = (e) => {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; console.log(refContainer.current.value);&nbsp; };&nbsp; useEffect(() => {&nbsp; &nbsp; console.log(refContainer.current);&nbsp; &nbsp; refContainer.current.focus();&nbsp; });&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <form className='form' onSubmit={handleSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type='text' ref={refContainer} />&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; <button type='submit'>submit</button>&nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; </>&nbsp; );};export default UseRefBasics;这是我给出的一般场景。您可以使用useEffect()并在状态更新时通过提供另一个参数useEffect(()=>{},[state1])或以您需要的任何方式获得焦点。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript