React:将 div 的宽度设置为图像的宽度
React: set width of a div to be the width of an image
我想让 div 的宽度与图像的宽度相同。这包括当您调整 window 大小时和图像自动调整大小时。目前,我尝试使用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>
用CSS就可以,不需要用react State
您现在使用 useEffect
的方式只会在安装组件时 运行 一次。您必须向调整大小事件添加一个事件侦听器,然后调用 setBasicInfoImageWidth
useEffect(() => {
window.addEventListener('resize', () => setBasicInfoImageWidth(
basicInfoImage.current.getBoundingClientRect().width
));
});
使用 CSS 解决此问题可能会更简单,但如果没有可用示例,则很难为您提供可用代码段。如果你添加一个 jsfiddle link 我很乐意帮助你 CSS
我想让 div 的宽度与图像的宽度相同。这包括当您调整 window 大小时和图像自动调整大小时。目前,我尝试使用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>
用CSS就可以,不需要用react State
您现在使用 useEffect
的方式只会在安装组件时 运行 一次。您必须向调整大小事件添加一个事件侦听器,然后调用 setBasicInfoImageWidth
useEffect(() => {
window.addEventListener('resize', () => setBasicInfoImageWidth(
basicInfoImage.current.getBoundingClientRect().width
));
});
使用 CSS 解决此问题可能会更简单,但如果没有可用示例,则很难为您提供可用代码段。如果你添加一个 jsfiddle link 我很乐意帮助你 CSS