【问题标题】:How do you use the Swiper callback methods in React?你如何在 React 中使用 Swiper 回调方法?
【发布时间】:2020-11-18 19:47:27
【问题描述】:

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

当点击其他东西时我需要这样做,以便 Swiper 可以更新(因为它最初是隐藏的),然后滑动到相关幻灯片。

目前,我在 jQuery 中 componentDidMount() 中有点击触发器,因为我正在将内容移植到 React 中。但如果更好的话,也很高兴改变这一点。单击发生在孙组件上。 而且我已经将 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>

感谢任何帮助或建议。

【问题讨论】:

    标签: reactjs swiper swiperjs


    【解决方案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/等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多