Swiper使用React的虚拟幻灯片中的renderExternal示例

时间:2017-11-24 07:05:08

标签: reactjs swiper

需要使用Swiper自定义React组件数组呈现为虚拟幻灯片

文档说明renderExternal可用于此,但API文档中没有示例http://idangero.us/swiper/api/#virtual

需要了解如何使用renderExternal函数完成此操作。

2 个答案:

答案 0 :(得分:0)

我不确定这是最好的方法,但这大致是我做的:

const mySwiper = new Swiper('.swiper-container', {
  virtual: {
    slides: this.props.array (or this.state.array)
    renderExternal: function(data){}
  }
})

然后在模板中显示您的组件:

<div className="swiper-container">
  <div className="swiper-wrapper">
    <MyComponent
      myProps="mySwiper.virtual.slides[mySwiper.activeIndex]"
    />
  </div>
</div>

(我是用Vue做的,而不是React)

答案 1 :(得分:0)

文档已更新,现在您可以找到an example有关如何在React中使用它的信息。作为参考,下面是给出的示例:

import React from 'react';
import Swiper from 'swiper/dist/js/swiper.esm.bundle';

export default class extends React.Component {
  constructor() {
    this.state = {
      // dummy slides data
      slides: (function () {
        var slides = [];
        for (var i = 0; i < 600; i += 1) {
          slides.push('Slide ' + (i + 1));
        }
        return slides;
      }()),
      // virtual data
      virtualData: {
        slides: [],
      },
    }
  }
  componentDidMount() {
    const self = this;
    const swiper = new Swiper('.swiper-container', {
      // ...
      virtual: {
        slides: self.state.slides,
        renderExternal(data) {
          // assign virtual slides data
          self.setState({
            virtualData: data,
          });
        }
      },
    });
  }
  render() {
    {/* ... */}
    <div className="swiper-container">
      <div className="swiper-wrapper">
        {/* It is important to set "left" style prop on every slide */}
        {this.state.virtualData.slides.map((slide, index) => (
          <div className="swiper-slide"
            key={index}
            style={{left: `${virtualData.offset}px`}}
          >{slide}</div>
        ))}
      </div>
    </div>
    {/* ... */}
  }
}