1

コンポーネント クラスがあり.slideToLoop().update()と を使用できるようにする必要がありますが、Swiper React ライブラリでこれらのメソッドを使用する方法を理解できませんでした。

他の何かがクリックされたときにこれを行う必要があります。これにより、Swiper が更新され (最初は非表示になっているため)、関連するスライドに slideTo できるようになります。

現時点では、componentDidMount()React に移植しているため、jQuery でクリック トリガーを使用しています。ただし、変更したほうがよい場合は、これも喜んで変更します。クリックは孫コンポーネントで発生します。そして、スワイパーインスタンスを状態に設定していますが、それは の後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 の return 部分:

<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 コールバック メソッドを使用して update/slideTo/etc を実行できます。

于 2020-12-02T16:26:18.303 に答える