使用Taro.createSelectorQuery動態計算tab切換效果tab的寬度

    const { itemMargin, padding } = this.props;
    let width = 0;
    this.systemInfo = await Taro.getSystemInfo();

    this.scale = this.systemInfo.screenWidth / 750;
    console.log('屏幕縮放比-------->', this.systemInfo);

    const query = Taro.createSelectorQuery().in(this.$scope);
    query
      .selectAll('#item')
      .boundingClientRect(res => {
        const listRef = res.filter(
          (item, index, arr) => index < arr.length / 2
        );

        listRef.forEach(ref => {
          width += ref.width + itemMargin * this.scale;
        });
        // 最終width爲減去一個最左邊的margin和加上兩個預留的兩端的padding值
        const containerWidth =
          width - itemMargin * this.scale + padding * this.scale * 2;
        this.setState({
          containerWidth,
          listRef
        });
      })
      .exec();

使用.in(this.$scope); 傳入this.$scope指明選擇器的選取範圍爲當前自定義組件 component 內;
在所有的操作最後必須調用.exec(), 來執行所有的代碼語句請求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章