【发布时间】:2020-01-27 07:25:56
【问题描述】:
请参考 React DOCS 中的this URL。此代码的一个版本也可在here 获得。
我知道在 Functional React Component 中,最好使用 useCallback 挂钩来创建一个 ref 回调,如上面的 React Docs URL 所示,但我想了解如果使用简单的arrow function(内联函数)用作 ref 回调。
所以,下面,我修改了上面 URL 中的代码,不使用 useCallback 钩子。相反,我只是使用常规的arrow function 作为 ref 回调。此外,我添加了两个 console.log 语句。这是代码,也可以在this URL 获得。
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [height, setHeight] = useState(0);
const measuredRef = node => {
console.log("Setting height. node = ", node);
if (node !== null) {
setHeight(node.getBoundingClientRect().height);
}
};
console.log("Rendering.");
return (
<div className="App">
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
加载此应用时,会打印以下内容(添加编号):
1. Rendering.
2. Setting height. node = <h1>Hello, world</h1>
3. Rendering.
4. Setting height. node = null
5. Setting height. node = <h1>Hello, world</h1>
6. Rendering.
为什么 ref 回调被调用了 3 次,为什么组件在初始加载时会渲染 3 次?
【问题讨论】:
标签: javascript reactjs react-hooks react-ref