如何检测何时加载图像,通过道具提供,并在React中更改状态?

Ser*_*nas 13 javascript state image loading reactjs

我想在加载最终头像时加载不同的图像(假化身).想法是检测何时加载道具图像并改变状态.可能吗?一些想法?谢谢!

class ImageUser extends React.Component {

constructor(props) {
    super(props);
    this.state = {userImageLoaded: false};
    let imageSrc = "";

    if (!this.props.userImage) {
        imageSrc = this.props.noUserImage;
    } else {
        imageSrc = this.props.userImage;
    }

    this.loadingImage = <img className={styles.imageUser}
                     src={this.props.loadingImage} alt="2"/>;

    this.userImage =
        <img onLoad={this.setState({userImageLoaded: true})}
             className={styles.imageUser} src={imageSrc}
             alt="1"/>;

}

render() {
    let image = "";
    if (this.state.userImageLoaded) {
        image = this.userImage;
    } else {
        image = this.loadingImage;
    }
    return (
        <div>
            {image}
        </div>
    );
}
}

export default ImageUser;
Run Code Online (Sandbox Code Playgroud)

Bri*_*and 21

有几种方法可以做到这一点,但最简单的方法是隐藏最终图像,然后在加载后将其翻转为可见图像.

JSBin演示

class Foo extends React.Component {
  constructor(){
    super();
    this.state = {loaded: false};
  }

  render(){
    return (
      <div>
        {this.state.loaded ? null :
          <div
            style={{
              background: 'red',
              height: '400px',
              width: '400px',
            }}
          />
        }
        <img
          style={this.state.loaded ? {} : {display: 'none'}}
          src={this.props.src}
          onLoad={() => this.setState({loaded: true})}
        />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我们如何为循环加载多个图像创建这样的图像 (3认同)
  • @Ranjith,您可以创建一个单独的“ Image”组件,使其具有自己的状态。然后,您不必担心键/ ID映射。 (3认同)
  • @Ranjith您将存储一个id / src值到布尔值的映射,以指示它们是否已加载。 (2认同)
  • @FakeRainBrigand谢谢,关于`&lt;div style = {{backgroundImage:'url($ {url})'}} /&gt;`之类的背景图像呢? (2认同)

lee*_*len 15

与 Brigand 接受的答案相同的答案,但带有 Hooks:

const Foo = ({ src }) => {
  const [loaded, setLoaded] = useState(false);

  return (
    <div>
      {loaded ? null : (
        <div
          style={{
            background: 'red',
            height: '400px',
            width: '400px'
          }}
        />
      )}
      <img
        style={loaded ? {} : { display: 'none' }}
        src={src}
        onLoad={() => setLoaded(true)}
      />
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)


grl*_*rll 15

使用元素引用的相同想法,但使用功能组件和带有打字稿的钩子:

import React from 'react';

export const Thumbnail = () => {
  const imgEl = React.useRef<HTMLImageElement>(null);
  const [loaded, setLoaded] = React.useState(false);

  const onImageLoaded = () => setLoaded(true);

  React.useEffect(() => {
    const imgElCurrent = imgEl.current;

    if (imgElCurrent) {
      imgElCurrent.addEventListener('load', onImageLoaded);
      return () => imgElCurrent.removeEventListener('load', onImageLoaded);
    }
  }, [imgEl]);

  return (
    <>
      <p style={!loaded ? { display: 'block' } : { display: 'none' }}>
        Loading...
      </p>
      <img
        ref={imgEl}
        src="https://via.placeholder.com/60"
        alt="a placeholder"
        style={loaded ? { display: 'inline-block' } : { display: 'none' }}
      />
    </>
  );
};
Run Code Online (Sandbox Code Playgroud)