在 React 中单击另一个元素时输入焦点
Focus input when another Element is clicked in React
在 React 中单击另一个元素时聚焦输入:
- 在输入元素上设置
ref
道具。 - 在另一个元素上设置
onClick
道具。 - 单击其他元素时,聚焦输入,例如
ref.current.focus()
。
应用程序.js
import {useRef} from 'react'; const App = () => { const ref = useRef(null); const handleClick = () => { ref.current.focus(); }; return ( <div> <input ref={ref} id="message" name="message" /> <hr /> <button onClick={handleClick}>Focus input</button> </div> ); }; export default App;
我们使用useRef钩子来创建一个 ref 对象,使我们能够访问输入元素。
useRef()
钩子可以传递一个初始值作为参数。该钩子返回一个可变的 ref 对象,其.current
属性被初始化为传递的参数。
Notice that we have to access the
current
property on the ref object to get access to the input
element on which we set the ref
prop.When we pass a ref prop to an element, e.g. <input ref={myRef} />
, React sets
the .current
property of the ref object to the corresponding DOM node.
We set the
onClick
prop on a button element, so every time the button is clicked, the handleClick
function is invoked.Note that this doesn’t have to be a button, you can set the onClick
prop on a
div
or any other element.
We used the
focus()
method to focus the input field in the handleClick
function.
The current
property on the ref gives us access to the input
element, so
calling ref.current.focus()
sets the focus on the input.