【问题标题】:ReactJS: how can I access parent element width from child component?ReactJS:如何从子组件访问父元素宽度?
【发布时间】:2019-11-09 00:14:33
【问题描述】:

已修复:我错过了将 .current 添加到我的参考...

我需要知道将包含我的组件的元素的宽度:查看 SO,我找到了一个解决方案,但它对我不起作用(它返回未定义):

import React from 'react';

import './Badger.css';

export default function Badger(props) {

  const refContainer = React.useRef(null);

  React.useLayoutEffect(()=>{
    // console.log(refContainer); I missed .current, now it works
    console.log(refContainer.current); // Change the line to this
  });

  const items = props.items ? props.items : [];

  return <div ref={refContainer}>{ items.join(", ") }</div>

}

本例中的父元素是一个 td:

<td>
  <Badger
    items={r.to}
    listContainerWidth={recipientsWidth}
  />
</td>

但它 console.log 返回“未定义”。如何获取父元素?

【问题讨论】:

  • 如果您解决了问题,欢迎您将其发布为答案并将您自己的解决方案标记为已接受(而不是作为对原始帖子的编辑)。

标签: javascript reactjs components


【解决方案1】:

我在我的参考文献中错过了 .current。如果您按以下方式编辑代码,它将解决问题!

React.useLayoutEffect(()=>{
  // console.log(refContainer); I missed .current, now it works
  console.log(refContainer.current); // Change the line to this
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多