我想获取状态的最新值并使用它内联样式,但它首先返回 0 值,然后渲染更新状态。但是,我无法将值分配给样式。
const ImageCard = ({ image: { alt_description, urls } }) => {
const [spans, setSpans] = useState(0);
const imageRef = useRef(null);
useEffect(() => imageRef.current.addEventListener('load', () => {
const height = imageRef.current.clientHeight;
const spans = Math.ceil(height / 10);
setSpans({ spans });
}));
return (
<div style={{ gridRowEnd: `span ${spans}` }}>
<img ref={imageRef} alt={alt_description} src={urls.regular} />
</div>
);
}
控制台输出:
10 0
{spans: 15}
{spans: 33}
...