【问题标题】:React: set width of a div to be the width of an imageReact:将 div 的宽度设置为图像的宽度
【发布时间】:2019-07-06 01:47:35
【问题描述】:

我想让 div 的宽度与图像的宽度相同。这包括调整窗口大小和图像自动调整大小时。目前,我尝试使用 useState,但在调整大小时它没有响应。

    const basicInfoImage = useRef();
    const basicInfoText = useRef();
    const [basicInfoImageWidth, setBasicInfoImageWidth] = useState();

    useEffect(() => {
        setBasicInfoImageWidth(
            basicInfoImage.current.getBoundingClientRect().width
        );
    });

      <img
        src={profilePic}
        alt="Profile Pic"
        className="About-basic-info-image"
        ref={basicInfoImage}
      />
      <p
        className="About-basic-info-text"
        ref={basicInfoText}
        style={{ width: basicInfoImageWidth }}
      >
        {basicInfoTextContent}
      </p>

【问题讨论】:

  • 通常,图像加载需要一些时间,在加载之前,浏览器不会知道它的大小。如果你记录basicInfoImage.current.getBoundingClientRect().width,你会得到一个非零值吗?如果是这样,img标签有一个onload事件,见stackoverflow.com/questions/39092859/…

标签: javascript html css reactjs responsive


【解决方案1】:

您现在使用useEffect 的方式只会在组件挂载时运行一次。您必须为 resize 事件添加一个事件侦听器,然后调用 setBasicInfoImageWidth

useEffect(() => {
    window.addEventListener('resize', () => setBasicInfoImageWidth(
        basicInfoImage.current.getBoundingClientRect().width
    ));
});

使用 CSS 解决这个问题可能会更简单,尽管如果没有工作示例,很难为您提供工作的 sn-p。如果您添加 jsfiddle 链接,我很乐意帮助您解决 CSS

【讨论】:

  • 是的,我更喜欢使用 CSS。我的jsfiddle我指定了div的宽度,但我不想这样做,而是当图像的高度为70%时,将div的宽度设置为图像的宽度。
  • 我不确定我是否 100% 关注,但试试这个jsfiddle.net/john_flournoy/zq3esmh5/2
  • 那是完美的。你能解释一下为什么在 div 中添加 display: inline-block 和 position: relative 和 position: absolute 在文本中可以实现这一点吗?
【解决方案2】:

你可以用 CSS 做,不需要使用 react State

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    相关资源
    最近更新 更多