1

我有一个组件类,需要能够使用.slideToLoop()and .update(),但无法弄清楚如何将这些方法与 Swiper React 库一起使用。

当单击其他内容时,我需要执行此操作,以便 Swiper 可以更新(因为它最初是隐藏的),然后滑动到相关幻灯片。

目前,componentDidMount()当我将内容移植到 React 中时,我在 jQuery 中有点击触发器。但如果更好的话,也很高兴改变这一点。单击发生在孙组件上。而且我将 swiper 实例设置为状态,但那发生在 之后componentDidMount,所以我无法从那里访问它。

代码:

  constructor(props) {
    super(props);
    this.state = {
      swiperIns: ''
    }
  }
  
  setSwiper = (swiper) => {
    this.setState({swiperIns: swiper}, () => {
      console.log(this.state.swiperIns);
    });
  }


  componentDidMount() {
    const { appStore } = this.props;
    if (!appStore.hasLoadedHomePage)
      appStore.loadHomePage().catch((ex) => null);
      
     const mySwiper = this.state.swiperIns;
     console.log(mySwiper); // returns ''
      
      $('.modal-trigger').on('click', function(e) {
         e.preventDefault();
         var modalToOpen = $(this).attr('data-modal-id');
         console.log(modalToOpen);
             if ($(this)[0].hasAttribute('data-slideindex')) {
                 const slideTo = parseInt($(this).attr('data-slideindex'));
                 // this.state.slideToLoop(slideTo);
             }

             $('#' + modalToOpen).show();
             $('body').addClass('modal-open');
             
             if ($('#' + modalToOpen).hasClass('modal--swiper')) {
                 // this.state.swiperIns.update();
             }
     });
  }

和 Swiper 的返回部分:

<Swiper onSwiper={ this.setSwiper } spaceBetween={0} slidesPerView={1} loop>
...
</Swiper>

任何帮助或建议表示赞赏。

4

1 回答 1

1

好的,所以我想通了。首先,向构造函数添加一个 ref:

constructor(props) {
    super(props);
    this.swiperRef = React.createRef();
}

在 中componentDidMount,像这样:

const mySwiper = this.swiperRef;

然后在 Swiper 元素上,将 ref 设置为 Swiper 实例,如下所示:

<Swiper ref={ this.swiperRef }...</Swiper>

然后在按钮点击/功能中,您可以使用this.swiperRef.current?.swiper.slideNext();或任何其他 Swiper 回调方法来更新/slideTo/等。

于 2020-12-02T16:26:18.303 回答