gpt4 book ai didi

javascript - `useRef` 和 `createRef` 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-03 12:54:38 25 4
gpt4 key购买 nike

当我偶然发现 useRef 时,我正在浏览 hooks 文档。 .

看看他们的例子......

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替换。

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>
</>
);
}

为什么我需要一个引用钩子(Hook)?为什么useRef存在?

最佳答案

不同之处在于 createRef 将始终创建一个新的引用。在基于类的组件中,您通常会在构造期间将 ref 放入实例属性中(例如 this.input = createRef())。函数组件中没有此选项。 useRef 负责每次返回与初始渲染时相同的引用。

下面是一个示例应用程序,演示了这两个函数的行为差异:

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);

Edit 1rvwnj71x3

关于javascript - `useRef` 和 `createRef` 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54620698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com