我想获取状态的最新值并以内联样式使用它,但是它首先返回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}
...
答案 0 :(得分:0)
您不需要useEffect
。您可以如下使用img标签的onLoad
事件:
const ImageCard = ({ image: { alt_description, urls } }) => {
const [spans, setSpans] = useState(0);
const imageLoaded = e => {
const height = e.currentTarget.clientHeight;
const spans = Math.ceil(height / 10);
setSpans({ spans });
};
//Dont forget to remove this line
console.log(spans);
return (
<div style={{ gridRowEnd: `span ${spans}` }}>
<img onLoad={imageLoaded} alt={alt_description} src={urls.regular} />
</div>
);
};