我偶然发现钩子文档useRef。
useRef
看他们的例子…
function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input element inputEl.current.focus(); }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
…似乎useRef可以替换为createRef。
createRef
function TextInputWithFocusButton() { const inputRef = createRef(); // what's the diff? const onButtonClick = () => { // `current` points to the mounted text input element inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
为什么我需要钩住裁判?为什么useRef存在?
不同之处在于,createRef它将始终创建一个新的引用。在基于类的组件中,通常会在构造期间将ref放入实例属性(例如this.input = createRef())。您在功能组件中没有此选项。useRef负责每次都返回与初始渲染相同的ref。
this.input = createRef()
这是一个示例应用程序,演示了这两个功能的行为差异:
import React, { useRef, createRef, useState } from "react"; import ReactDOM from "react-dom"; function App() { const [renderIndex, setRenderIndex] = useState(1); const refFromUseRef = useRef(); const refFromCreateRef = createRef(); if (!refFromUseRef.current) { refFromUseRef.current = renderIndex; } if (!refFromCreateRef.current) { refFromCreateRef.current = renderIndex; } return ( <div className="App"> Current render index: {renderIndex} <br /> First render index remembered within refFromUseRef.current: {refFromUseRef.current} <br /> First render index unsuccessfully remembered within refFromCreateRef.current: {refFromCreateRef.current} <br /> <button onClick={() => setRenderIndex(prev => prev + 1)}> Cause re-render </button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);