不同之处在于,
createRef它将始终创建一个新的引用。在基于类的组件中,通常会在构造期间将ref放入实例属性(例如
this.input =createRef())。您在功能组件中没有此选项。
useRef负责每次都返回与初始渲染相同的ref。
这是一个示例应用程序,演示了这两个功能的行为差异:
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);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)