[英]Declare variable only once BEFORE render in react?
I need to grab the height of a div in React using useRef
and assign it to a variable, defaultHeight
.我需要使用
useRef
在 React 中获取 div 的高度并将其分配给变量defaultHeight
。
const jselectRef = useRef<HTMLButtonElement>(null)
let defaultHeight: number | undefined
console.log(defaultHeight) // returns undefined
useEffect(() => {
if (jselectRef.current !== null) {
defaultHeight = jselectRef.current.offsetParent?.clientHeight
console.log(defaultHeight) // returns the height of the div (40)
}
}, [])
console.log(defaultHeight) // returns undefined, even after first page render
Since useEffect
runs after the page is rendered, I need to declare the defaultHeight
variable outside of it, but assign it to the ref inside of it.由于
useEffect
在页面呈现后运行,因此我需要在其外部声明defaultHeight
变量,但将其分配给其中的 ref。
However, when I declare the variable outside of useEffect
, then the variable gets reset to undefined every time my component re-renders.但是,当我在
useEffect
之外声明变量时,每次我的组件重新渲染时,变量都会重置为undefined 。
Is there a way to tell React to only declare the variable let defaultHeight: number | undefined
有没有办法告诉 React 只声明变量
let defaultHeight: number | undefined
let defaultHeight: number | undefined
once, before page load?在页面加载之前
let defaultHeight: number | undefined
一次? Then once useEffect
sets the variable based on the ref, leave it alone?那么一旦
useEffect
根据 ref 设置变量,就不管它了吗?
useEffect
doesn't work here, because then the first load will be undefined
, which triggers TypeScript. useEffect
在这里不起作用,因为第一次加载将是undefined
,这会触发 TypeScript。
I don't think useMemo
would apply here since we are just declaring the variable, but I could be mistaken.我不认为
useMemo
会在这里应用,因为我们只是在声明变量,但我可能弄错了。
You could use another ref.你可以使用另一个参考。 (This is largely what refs are for--variables that persist across renders--so this seems like the best option to me.)
(这在很大程度上是 refs 的用途——在渲染中持续存在的变量——所以这对我来说似乎是最好的选择。)
const defaultHeight = useRef();
useEffect(() => {
// ...
defaultHeight.current = 123;
})
Or use state, but note that this could trigger a re-render, which you may not want.或使用 state,但请注意,这可能会触发重新渲染,您可能不希望这样做。
const [defaultHeight, setDefaultHeight] = useState();
useEffect(() => {
// ...
setDefaultHeight(123);
}, [])
Or you could move it outside the component altogether, but as Giorgi Moniava rightly points out in a comment below, this approach will cause interference if the component is used in multiple places--they'll all update the same variable--and is therefore not recommended .或者您可以将它完全移到组件之外,但正如Giorgi Moniava 在下面的评论中正确指出的那样,如果在多个地方使用该组件,这种方法会造成干扰——它们都会更新同一个变量——因此不推荐。 Leaving this option here just to note why you shouldn't do it this way.
在这里留下这个选项只是为了说明为什么你不应该这样做。
let defaultHeight;
function MyComponent () {
useEffect(() => {
// ...
defaultHeight = 123;
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.