我正在尝试将 Class 组件转换为 Hook 组件,但很难转换一些内容:
sceneSetup = () => {
const width = this.el.clientWidth;
const height = this.el.clientHeight;
this.el.appendChild(this.renderer.domElement);
};
1) this.el?
如何将其转换为钩子(Hook)组件?
另外在我的渲染方法中我返回这个:
render() {
return(
<div ref={ref => (this.el = ref)} />
)
}
2)div如何转化为hook?
最佳答案
How would this.el? this be translated into a hook component?
使用useRef钩子(Hook)。
2) How does the div translate into a hook?
只需使用 el
引用返回 div
即可。
function Scene() {
const el = useRef(null);
return <div ref={el} /> // init el ref
}
或者,您也可以使用 callback ref用于测量节点尺寸。
function Scene() {
const [rect, setRect] = useState(null);
const callbackRef = useCallback(node => {
if (node !== null) {
setRect(node.getBoundingClientRect());
}
}, []);
return <div ref={callbackRef} /> // use callback ref
}
关于reactjs - 将类重构为 Hook 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58163867/