代码之家  ›  专栏  ›  技术社区  ›  theJuls

当img不存在时,使用ReactJS替换为nothing

  •  1
  • theJuls  · 技术社区  · 6 年前

    我想用react组件中的任何内容替换不存在的图像。有什么方法可以让我使用 onError 以某种方式把什么都放在图像的地方?

    render() {
      return (
        <img src={myImage} onError={(e)=>{/*Do something to replace the image with nothing*/}}/>
      )
    }
    

    或者,我可以使用jquery来检测图像,如果没有找到,我只需 return null 在我的 render 功能。但从目前的情况来看,我也无法做到这一点。这就是我的函数当前的样子:

      checkIfImageExists () {
        return $.get(myImage)
          .done(() => console.warn('found it!', myImage))
          .fail(() => console.warn('didnt fin it!', myImage))
      }
    
    render() {
          console.warn(this.checkIfImageExists())
        if (!this.checkIfImageExists().status) {
          return null
        }
      return (
        <img src={myImage}/>
      )
    }
    

    问题是它永远找不到。我的代码有什么问题吗?如何修复它,以便在找不到图像时不渲染任何内容?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Estus Flask    6 年前

    这两种情况都需要使用组件 state 要异步处理图像,请执行以下操作:

    state = { imgSrc: myImage } // depends on where myImage comes from
    
    onImageError = () => {
      this.setState({ imgSrc: null })
    }
    
    render() {
      return (
        {this.state.imgSrc && <img src={this.state.imgSrc} onError={this.onImageError }/>}
      )
    }
    
        2
  •  1
  •   Egor Stambakio    6 年前

    您可以使用CSS隐藏图像 display: none 展示给大家看 onload :

    class NonEmptyImage extends React.Component {
      state = {
        visible: false
      }
      
      handleLoad = _ => this.setState({ visible: true });
      
      render() {
        const { src } = this.props;
        const { visible } = this.state;
        return (
          <img
            src={src}
            onLoad={this.handleLoad}
            style={{ display: visible ? 'initial' : 'none' }}
          />
        )
      }
    }
    
    ReactDOM.render(<NonEmptyImage src='https://upload.wikimedia.org/wikipedia/en/thumb/4/4d/SpongeBob_SquarePants_characters_cast.png/300px-SpongeBob_SquarePants_characters_cast.png'/>, document.querySelector("#fw33f4w5"))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="fw33f4w5"></div>

    改变 src

    如果你讨厌类,下面是一个函数的工作示例:

    function NonEmptyImage({ src }) {
      let ref;
    
      return (
        <img
          ref={el => ref = el}
          src={src}
          onLoad={_ => ref.style.display = 'initial'}
          style={{ display: 'none' }}
        />
      )
    }
    
    ReactDOM.render(<NonEmptyImage src='https://upload.wikimedia.org/wikipedia/en/thumb/4/4d/SpongeBob_SquarePants_characters_cast.png/300px-SpongeBob_SquarePants_characters_cast.png' />, document.querySelector("#fw33f4w5ert"))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="fw33f4w5ert"></div>