如何在完全基于功能组件的 React 应用程序中获取元素的大小? [英] How to get size of an element in an react app that is totally based on functional components?

查看:40
本文介绍了如何在完全基于功能组件的 React 应用程序中获取元素的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完全由功能组件构建的 React 应用程序.我想获取元素在屏幕上呈现后的高度以相应地更改其父元素的大小.

有针对基于类的应用程序的解决方案,但我找不到针对功能组件的解决方案.

我从答案中尝试了这个解决方案,但它没有运行 useEffect 钩子

这里是从我的组件中提取的代码

import React, {useRef, useEffect} from 'react';进口 {菜单容器,灰盒,包装器} 来自'../LayersMenu/LayerMenu.styles';export const Component = ({ category, showStatistics }) =>{const grayBoxRef= useRef(null);const wrapperRef= useRef(null);const testRef= useRef(null);useEffect(()=>{const height = wrapperRef.current.offsetHeight;console.log(height,'check');}, [wrapperRef])useEffect(()=>{常量高度 = testRef.current.offsetHeight;console.log(height,'check2');},[testRef]);返回 (<MenuContainer ref={testRef}><GrayBox ref={grayBoxRef}><Wrapper ref={wrapperRef} hasAnyAllowedStats={showStatistics}></包装器></GrayBox></MenuContainer>);};

PS:接受的答案对我的答案不起作用,但它适用于他在答案中添加的项目,所以我猜我的项目结构有问题或不完全确定.

非常感谢您的回答

解决方案

代替使用带有 componentDidMount 的类组件,有一个名为 useEffect 的钩子可以帮助您捕捉不知何故组件的渲染状态.

获取渲染的 DOM 元素高度的解决方案可以是以下带有功能组件的:

 const YourComponent = () =>{const inputRef = useRef(null);useEffect(() => {常量高度 = inputRef.current.offsetHeight;console.log('输入高度', 高度);}, [inputRef]);返回 <><input ref={inputRef} type="text" defaultValue="testing"/></>}

说明:

useRef 钩子将帮助您在组件的生命周期内保持对对象的引用,如文档所述:

<块引用>

useRef 返回一个可变的 ref 对象,其 .current 属性被初始化为传递的参数 (initialValue).返回的对象将在组件的整个生命周期内持续存在.

一旦您将 useEffectuseRef 结合使用,就像在上述解决方案中一样,您将获得预期的结果.对于 useEffect 钩子,文档解释了:

<块引用>

传递给 useEffect 的函数将在渲染提交到屏幕后运行.

inputRef 传递给依赖数组将在useEffectinput 元素更改时触发传递的函数.然后代码计算组件的高度,在这种情况下它只是一个 input 元素.这可以是任何 DOM 元素,就像 div 一样.

更新:

根据您更新的问题,解决方案是 forwardRef,请阅读文档:

<块引用>

引用转发是一种自动将引用通过组件传递到其子组件的技术.

通过这种技术,您可以在父组件中访问子组件的属性,例如:内部

元素的高度,代码是什么可以用于其他目的.

在您的子功能组件中,代码应该使用 forwardRef 来访问内部 DOM 元素,如下所示:

import React, { forwardRef } from 'react';//...const YourComponent = forwardRef((props, ref) => {返回 <><input ref={ref} type="text" defaultValue="testing"/></>});

然后在父组件中使用如下:

const componentRef = useRef(null);useEffect(() => {const {offsetHeight} = componentRef.current;console.log('componentRef height', offsetHeight);}, [componentRef]);返回 <><你的组件引用={componentRef}/></>

如果您有兴趣进一步了解,请在此处找到文档:将引用转发到 DOM 组件

请为您的场景找到一个可行的 GitHub 解决方案,我刚刚为表示而构建:norbitrial/react-forwarding-ref-example

希望这能给您进一步进行的想法.

I have a react app that is purely built with functional components. I want to get the height of an element after it has been rendered on screen to change size of it's parent accordingly.

There are solutions for class based apps but I couldn't find any for functional components.

i tried this solution from answers but it is not running the useEffect hook

here is extracted code from my component

import React, {useRef, useEffect} from 'react';
import {
    MenuContainer,
    GrayBox,
    Wrapper

} from '../LayersMenu/LayerMenu.styles';


export const Component = ({ category, showStatistics }) => {
    const grayBoxRef= useRef(null);
    const wrapperRef= useRef(null);
    const testRef= useRef(null);
    useEffect(()=>{
        const height = wrapperRef.current.offsetHeight;
        console.log(height,'check');
      }, [wrapperRef])
    useEffect(()=>{
        const height = testRef.current.offsetHeight;
        console.log(height,'check2');
    },[testRef]);
    return (
        <MenuContainer ref={testRef}>
            <GrayBox ref={grayBoxRef}>
                <Wrapper ref={wrapperRef} hasAnyAllowedStats={showStatistics}>
                </Wrapper>
            </GrayBox>
        </MenuContainer>
    );
};

PS: accepted answer didn't work for my answer but it works for the project he added in answer works so i guess there is something wrong with my project structure or something not entirely sure.

Thanks alot for answer

解决方案

Instead of using class component with componentDidMount there is a hook called useEffect which can help you to catch somehow the rendered state of the component.

The solution to get height of a rendered DOM element can be the following with functional component:

 const YourComponent = () => {
   const inputRef = useRef(null);
   useEffect(() => {
      const height = inputRef.current.offsetHeight;
      console.log('Input height', height);   
   }, [inputRef]);

   return <>
     <input ref={inputRef} type="text" defaultValue="testing" />
   </>
}

Explanation:

useRef hook will help you to keep the reference for your object for the life of your component, as the documentation states:

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Once you use useEffect combined with useRef just like in the above solution you will get the expected result. For useEffect hook the documentation explains:

The function passed to useEffect will run after the render is committed to the screen.

Passing inputRef to the dependency array will trigger the passed function on change of the input element for useEffect. Then the code calculates the height of your component which in this case just an input element. This can be any DOM element, just like a div.

UPDATE:

From your updated question, the solution is forwardRef, read in the documentation:

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

With this technique you can access the child component's properties in the parent component e.g.: height of an internal <div> or <input> element what the code can use for further purposes.

In your child functional component, the code should use forwardRef in order to access internal DOM elements, just like below:

import React, { forwardRef } from 'react';

// ...

const YourComponent = forwardRef((props, ref) => {
   return <>
      <input ref={ref} type="text" defaultValue="testing" />
   </>
});

Then use in the parent component as the following:

const componentRef = useRef(null);
useEffect(() => {
    const {offsetHeight} = componentRef.current;
    console.log('componentRef height', offsetHeight);   
}, [componentRef]);

return <>
    <YourComponent ref={componentRef} />
</>    

If you are interested further then please find the documentation here: Forwarding refs to DOM components

Please find a working GitHub solution for your scenario what I just built up for representation: norbitrial/react-forwarding-ref-example

Hope this gives you the idea to proceed further.

这篇关于如何在完全基于功能组件的 React 应用程序中获取元素的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆