1

我真的很喜欢“react-responsive-carousel”,它完全符合我的要求。

更多细节: https ://www.npmjs.com/package/react-responsive-carousel

但是我意识到这个提供的演示示例使用静态图像,放置在单独的“Carousel.js”文件中。

就我而言,我想在 Carousel 中加载图像,我在运行时使用 API 获取这些图像。我不知道如何实现这种行为。

目前以下是我的应用程序的设置: 文件:Carousel.js

import React from "react";
import { Carousel } from "react-responsive-carousel";

export default () => (
  <Carousel autoPlay infiniteLoop='true'>
    <div>
      <img src="http://example.com/image/32.png" />
      <p className="legend">Image 1</p>
    </div>
    <div>
      <img src="http://example.com/image/34.png" />
      <p className="legend">Image 2</p>
    </div>
    <div>
      <img src="http://example.com/mockups/image/9.png" />
      <p className="legend">Image 3</p>
    </div>
    <div>
      <img src="http://example.com/image/32.png" />
      <p className="legend">Image 4</p>
    </div>
    <div>
      <img src="http://example.com/image/34.png" />
      <p className="legend">Image 5</p>
    </div>
  </Carousel>
);

在我的App.js文件中,我只是通过以下方式使用它:

<div>
<div className="my-carousel">
<Carousel />
</div>
</div>
4

1 回答 1

1

这是一个基本流程,您可以根据需要进行调整:

  1. 首先,您必须获取图像。
  2. 之后,您必须将图像保持在组件的状态。
  3. 最后,<Carousel />用状态的图像渲染 。

这是一个伪代码:

import React from 'react'
import { Carousel } from 'react-responsive-carousel'

class App extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      images: null
    }
  }

  componentDidMount() {
    // #1. First of all you have to fetch the images.
    fetch('https://example.com/images-api-endpoint')
      .then(response => response.json()) // If it's a JSON response, you have to parse it firstly
      .then(images => this.setState({ images })) // #2. After that you have to keep the images in the component's state.
  }

  render () {
    const { images } = this.state

    if (!images) return <div>Images are not fetched yet!</div>

    // #3. Finally, render the `<Carousel />` with the state's images.
    return <Carousel autoPlay infiniteLoop='true'>
      {
        images.map( image => {
          return <div>
            <img src={ image.path } />
            <p className="legend">{ image.name }</p>
          </div>
        })
      }
    </Carousel>
  }
}

请记住,上述流程中没有包含一些概念,因为它们超出了问题的范围。例如:

  1. 显示加载指示器,同时获取图像。
  2. 错误处理,如果 API 请求失败。
于 2018-11-29T14:10:21.550 回答