首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React:使用useRef和钩子获取映射图像的clientHeight

React:使用useRef和钩子获取映射图像的clientHeight
EN

Stack Overflow用户
提问于 2021-08-10 21:35:22
回答 1查看 117关注 0票数 1

我正在构建一个动态图像网格,并尝试找到每个图像的实际高度(以像素为单位),以相应地调整布局。

我的问题是当尝试访问未定义的ref.current.clientHeight时。我试着关注这篇文章的How can I use multiple refs for an array of elements with hooks?,但无法访问图像的高度

代码语言:javascript
运行
复制
    const Grid = ({ arr }) => {
    const ref = useRef([])
    const arrLength = arr.length;

    const [elRefs, setElRefs] = useState([])

    useEffect(()=> {
        setElRefs(elRefs => (
            Array(arrLength).fill().map((_, i) => elRefs[i] || createRef())
          ));
        },[arrLength])

    return (
        <Container>
            {arr && arr.length !== 0 ? arr.map((o, i) => {

           // I want to access the clientHeight here to pass to the GridCard component as a prop

                return (
                    <GridCard
                        key={i}
                        data={o}
                        width={"280px"}
                        height={"auto"}
                        ref={elRefs[i]}
                    >
                    </GridCard>

                )
            }) : null}
        </Container>
    );
}
export default Grid;
EN

回答 1

Stack Overflow用户

发布于 2021-08-10 22:14:50

请看一下react-use-measure包。

示例用法:

代码语言:javascript
运行
复制
const [ref, bounds] = useMeasure({ polyfill: ResizeObserver });
return (
    <Grid
      container
      ref={ref}
      className={clsx(classes.root, bounds.width <= 300 ? classes.narrow : undefined)}
      ...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68733706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档