0

我想获取状态的最新值并使用它内联样式,但它首先返回 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}
...
4

1 回答 1

0

你不需要useEffect这个。您可以使用onLoadimg 标签的事件如下:

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>
  );
};

工作代码沙箱示例

于 2020-05-07T18:08:54.267 回答