React-JS如何在加载图库之前使预加载器图标出现?

时间:2019-06-15 22:08:39

标签: javascript reactjs

我有一个通过依赖项react-lightbox-component进入的灯箱画廊。 一切工作正常,但在画廊弹出屏幕之前,我想显示一个来自超棒字体的预加载器图标:

<i className="fa fa-spinner"></i>

真棒字体已经安装在我的应用程序中并且可以正常工作。如何在灯箱画廊中添加预加载器?

反应灯箱组件文档:

https://www.npmjs.com/package/react-lightbox-component

我的组件:

import React, { Component } from 'react'
import Lightbox from 'react-lightbox-component';


class PortfolioPage extends Component {
  constructor(props) {
    super(props);
    this.state = {     
      resultPhotos: []
    }
  }

  componentDidMount() {
    this.setState({  
      resultPhotos: this.props.data.photos
    })
  }

  render() {
    const { resultPhotos } = this.state;   
    const renderImages = resultPhotos && resultPhotos.map((photo, index) => {
      return (
        {
          src: `../images/${photo}`,
          key: index
        }
      )
    })

    return (
      <div>
        <Lightbox images={renderImages} />
      </div>
    )
  }
}

export default PortfolioPage

2 个答案:

答案 0 :(得分:1)

尝试这种方式:

  • 我更改了componentDidMount以便设置已解析的照片。
  • 我还用两种渲染方式更改了return部分。

希望有帮助。

import React, { Component } from 'react'
import Lightbox from 'react-lightbox-component';


class PortfolioPage extends Component {
  constructor(props) {
    super(props);
    this.state = {     
      resultPhotos: []
    }
  }

  componentDidMount() {
    const parsePhotos = arr =>
        arr.map((photo, index) => ({
            src: `../images/${photo}`,
            key: index
        }));
    const { data } = this.props;
    if (data && data.photos) {
        this.setState({  
            resultPhotos: [...parsePhotos(data.photos)]
        })
    }

  }

  render() {
    const { resultPhotos } = this.state;   

    return (
      <div>
        { !!resultPhotos.length
            ? (<Lightbox images={resultPhotos} />)
            : (<i className="fa fa-spinner"></i>)
        }
      </div>
      )
  }
}

export default PortfolioPage


更新

与@claudiobitar聊天后,我们发现依赖项react-lightbox-component存在问题。

It is not a problem of the PortfolioPage.jsx, but the Lightbox component.
If it is a dependency issue there is no much to do, sorry, just try another one.
If a dependency has less than 1000 downloads per week is a bad sign.

答案 1 :(得分:0)

componentDidMount() {
    this.setState({  
      resultPhotos: this.props.data.photos,
      isReady = false,
    })
  }
render() {
    const { resultPhotos, isReady } = this.state;   
    const renderImages = resultPhotos && resultPhotos.map((photo, index) => {
      return (
        {
          src: `../images/${photo}`,
          key: index
        }
      )
    })

    if (!isReady) return (<i className="fa fa-spinner"></i>);

    return (
      <div>
        <Lightbox images={renderImages} />
      </div>
    )
  }

在这里,您几乎拥有所需的一切,只是找到放置this.setState({isReady: true})的正确位置。