SoYoung210 / soso-tip

🍯소소한 팁들과 정리, 버그 해결기를 모아두는 레포
24 stars 0 forks source link

React image preload (and imageFetchState) #31

Open SoYoung210 opened 4 years ago

SoYoung210 commented 4 years ago

Desc

이미지 onLoad 를 통해 이미지 로드가 완료된 시점에 필요한 작업들을 수행할 수 있지만, 이를 조금더 효율적으로 관리할 수 있다.

componentDidMount() {
  const img = new Image();
  img.src = Newman; // by setting an src, you trigger browser download

  img.onload = () => {
    // when it finishes loading, update the component state
    this.setState({ imageIsReady: true });
  }
}

위와같은 코드로, 필요한 이미지 파일을 preload하고 이미지에 관련된 localState를 변경하는 방식으로 하면 된다.

Ref

StackOverflow