programing

동형/유니버설 반응의 Image onLoad 이벤트 - 이미지 로드 후 이벤트 등록

kingscode 2023. 3. 12. 12:40
반응형

동형/유니버설 반응의 Image onLoad 이벤트 - 이미지 로드 후 이벤트 등록

이형 렌더링된 페이지 이미지는 메인 전에 다운로드 할 수 있습니다.script.js파일입니다. 그래서 이미지는 이미 로드되어 있습니다.react등록하세요onLoadevent - 이 이벤트를 트리거하지 않습니다.

script.js

constructor(props) {
    super(props);
    this.handleImageLoaded = this.handleImageLoaded.bind(this);
}

handleImageLoaded() {
    console.log('image loaded');
} 

render() {
    return (
        <img src='image.jpg' onLoad={this.handleImageLoaded} />
    );
}

시나리오 1 -image.jpg보다 크다script.js

image.jpg는 script.jpg보다 큽니다.

이 시나리오에서는 모든 것이 정상적으로 동작하고 있습니다.이벤트는 이미지가 최종적으로 로드되기 전에 등록되므로 콘솔에서는image loaded메세지.


시나리오 2 -image.jpg보다 작다script.js

image.jpg는 script.jpg보다 작습니다.

이 시나리오는 투고 처음에 설명되어 있는 문제를 확인할 수 있습니다. onLoad이벤트는 트리거되지 않습니다.


질문.

내가 할 수 있는 일은onLoad어떤 사건입니까?


편집: 간단한 답변 구현

렌더에서 이미지가 준비되었는지 여부를 감지하려면complete순수 자바스크립트상의 재산img오브젝트:

constructor(props) {
    super(props);
    this.state = { loaded: false };
    this.handleImageLoaded = this.handleImageLoaded.bind(this);
    this.image = React.createRef();
}

componentDidMount() {
    const img = this.image.current;
    if (img && img.complete) {
        this.handleImageLoaded();
    }
}

handleImageLoaded() {
    if (!this.state.loaded) {
        console.log('image loaded');
        this.setState({ loaded: true });
    }
} 

render() {
    return (
        <img src='image.jpg' ref={this.image} onLoad={this.handleImageLoaded} />
    );
}

확인하실 수 있습니다.complete적용하기 전에 이미지의 속성onload이벤트입니다.

if (!img.complete) {
    // add onload listener here
}

Hooks를 사용하면 이 모든 것이 좀 더 깔끔해집니다.


const useImageLoaded = () => {
  const [loaded, setLoaded] = useState(false)
  const ref = useRef()

  const onLoad = () => {
    setLoaded(true)
  }

  useEffect(() => {
    if (ref.current && ref.current.complete) {
      onLoad()
    }
  })

  return [ref, loaded, onLoad]
}

const SomeComponent = ({ src }) => {
  const [ref, loaded, onLoad] = useImageLoaded()

  return (
    <div>
      <img ref={ref} onLoad={onLoad} src={src} alt="" />
      {loaded && <h1>Loaded!</h1>}
    </div>
  )
}

또 다른 방법은 ref를 사용하여 다음 두 가지 시나리오를 모두 커버하는 것입니다.

<img
  ref={(input) => {
    // onLoad replacement for SSR
    if (!input) { return; }
    const img = input;

    const updateFunc = () => {
      this.setState({ loaded: true });
    };
    img.onload = updateFunc;
    if (img.complete) {
      updateFunc();
    }
  }}
  src={imgSrc}
  alt={imgAlt}
/>

src 로드가 실패해도 img.complete는 true입니다.

complete - 브라우저가 이미지 가져오기를 완료한 경우 성공 여부에 관계없이 true인 부울 값을 반환합니다.이미지에 src 값이 없는 경우에도 true가 표시됩니다.

  1. naturalWidth를 img 로드의 성공 여부를 결정하는 요소로 사용합니다.
    state = {
        isLoading: true,
        hasError: false,
    }

    myRef = React.createRef();

    componentDidMount() {
        const img = this.myRef.current;

        if (img && img.complete) {
            if (img.naturalWidth === 0) {
                this.handleOnError();
            } else {
                this.handleImageLoaded();
            }
        }
    }

    handleImageLoaded = () => {
        if (this.state.isLoading) {
            this.setState({ isLoading: false });
        }
    }

    handleOnError = () => {
        this.setState({ hasError: true });
    }

    render() {
        return (
            <img
                src={src}
                alt={alt}
                ref={this.myRef}
                onError={this.handleOnError}
                onLoad={this.handleOnLoad}
            />
        );
    }
  1. 또 다른 방법은 componentDidSeteventHandler에 check 이미지를 추가하여 eventListeners를 처리하는 이미지를 체크하는 것입니다.
componentDidMount() {
   const testImg = new Image();
   testImg.onerror = this.handleOnError;
   testImg.onload = this.handleImageLoaded;
   testImg.src = this.props.src; // important to set eventlisteners before src
}

<img
    src={this.props.imageUrl}
    onLoad={this.handleImageLoaded.bind(this)}
    onError={this.handleImageErrored.bind(this)}
/>

언급URL : https://stackoverflow.com/questions/39777833/image-onload-event-in-isomorphic-universal-react-register-event-after-image-is

반응형