Contents

横向 瀑布流列表

需求

/waterfall-list-horizontal/media/17007216190381/17007220568253.png

效果展示 /waterfall-list-horizontal/media/17007216190381/17007221852854.gif

源码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import React, { useEffect, useRef, useState } from "react";
import HBImage from "../../../../components/image/HBImage";
import { px2dp } from "../../../../utils/ScreenUtils";
import { MasonryFlashList } from "@shopify/flash-list";
import { bookOpenChoices } from "app/service/MarkService";
import * as indexUtil from "app/utils/index";

const itemWidth = px2dp(12 + 86.5 + 251.5);
const itemHeight = px2dp(139);
const itemSpace = px2dp(17);

const UserChooseBook = (props) => {
  const { selectedSex, marks } = props;

  const [dataList, setDataList] = useState([]);

  const listViewRef = useRef(null);

  const { onScrollBeginDrag, onScroll } = useListViewAutoScrollAnimate({
    listViewRef: listViewRef,
    framesPerSecond: 40, // 1000/40 = 25帧/秒
    offsetPerFrame: 1,
    totalScrollDistance:
      (itemWidth * Math.max(0, Math.max(0, dataList?.length || 0) - 1)) / 2,
    disableAnimate: false,
  });

  useEffect(() => {
    bookOpenChoices({
      gender: selectedSex || "girl",
      ...(marks ? { marks: marks } : {}),
    }).then((res) => {
      setDataList(res.books);
    });
  }, []);

  const renderItem = (props) => {
    console.log("renderItem props:", props);
    return (
      <BookItem
        key={props.item?.bookId}
        {...props}
        onPress={() => {
          goNext(props.item.bookId);
        }}
      />
    );
  };

  const goNext = (bookId) => {};

  return (
    <View style={styles.container}>
      <Text style={styles.title}>进站必读</Text>
      <View style={styles.scrollContainer}>
        <MasonryFlashList
          ref={listViewRef}
          estimatedItemSize={/* itemStyles.container.height */ 100}
          data={dataList}
          keyExtractor={(item, index) => item?.["bookId"]}
          initialNumToRender={5}
          numColumns={2}
          renderItem={renderItem}
          showsVerticalScrollIndicator={false}
          onScrollBeginDrag={onScrollBeginDrag}
          onScroll={onScroll}
        />
      </View>
      <TouchableOpacity style={styles.button} onPress={() => goNext()}>
        <Text style={styles.buttonTitle}>{"跳过"}</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    paddingLeft: itemSpace,
  },
  title: {
    marginTop: px2dp(90),
    color: "#101417",
    fontWeight: "bold",
    fontSize: px2dp(17),
    lineHeight: px2dp(24),
  },
  scrollContainer: {
    marginTop: px2dp(72),
    width: itemHeight * 2 + itemSpace * 2, //px2dp(139 * 2 + 17),
    height: px2dp(375),
    transform: [{ rotate: "270deg" }],
  },
});


export default UserChooseBook;

// -----  -----  -----  ----- hooks  -----  -----  -----  -----

const useListViewAutoScrollAnimate = ({
  listViewRef,
  framesPerSecond,
  offsetPerFrame,
  totalScrollDistance,
}) => {
  const scrollInterval = Math.floor(1000 / framesPerSecond); // 每次滚动之间的间隔,每秒动画的帧数
  const scrollDistance = offsetPerFrame; // 控制每scrollInterval 滚动的距离

  const [disabled, setDisabled] = useState(false);

  const scrollIntervalId = useRef(null);

  const currentScrollDistance = useRef(0);

  useEffect(() => {
    const stopAutoScroll = () => {
      clearInterval(scrollIntervalId.current);
    };

    if (totalScrollDistance > 10 && !disabled) {
      setTimeout(() => {
        startAutoScroll();
      }, 100);
    }

    return () => {
      stopAutoScroll();
    };
  }, [totalScrollDistance, disabled]);

  const scroll = () => {
    const nextDistance = Math.min(
      totalScrollDistance,
      currentScrollDistance.current + scrollDistance
    );
    listViewRef.current.scrollToOffset({
      offset: nextDistance,
      animated: false,
    });

    currentScrollDistance.current = nextDistance;
    if (currentScrollDistance.current >= totalScrollDistance) {
      currentScrollDistance.current = 0;
    }
  };

  const startAutoScroll = () => {
    scrollIntervalId.current = setInterval(scroll, scrollInterval);
  };

  const onScrollBeginDrag = () => {
    setDisabled(true);
  };

  const onScroll = (e) => {
    currentScrollDistance.current = e.nativeEvent.contentOffset.y;
  };

  return {
    onScrollBeginDrag,
    onScroll,
  };
};

// -----  -----  -----  ----- component  -----  -----  -----  -----

const BookItem = (props) => {
  const { item, index, onPress } = props;
  const { coverUrl, bookName: title } = item;

  const _coverUrl = indexUtil.getImageUrl(
    indexUtil.DOMAIN_PICAPP,
    coverUrl,
    indexUtil.IMG_BOOK_COVER_LIST
  );
  return (
    <TouchableOpacity
      style={[itemStyles.container, index == 1 ? { marginTop: 100 } : {}]}
      onPress={onPress}
    >
      <View style={itemStyles.transformContainer}>
        <HBImage source={{ uri: _coverUrl }} style={itemStyles.cover} />
        <View style={itemStyles.infoContainer}>
          <Text style={itemStyles.title} numberOfLines={1}>
            {title}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};

const itemStyles = StyleSheet.create({
  container: {
    height: itemWidth,
    width: itemHeight,
    borderRadius: px2dp(12),
    overflow: "hidden",
    backgroundColor: "#F4F8FA",
    marginBottom: itemSpace,
  },
  transformContainer: {
    width: itemWidth,
    height: itemHeight,
    transform: [
      { rotate: "90deg" },
      { translateX: (itemWidth - itemHeight) / 2 },
      { translateY: (itemWidth - itemHeight) / 2 },
    ],
    flexDirection: "row",
    alignItems: "center",
  },
  cover: {
    width: px2dp(86),
    height: px2dp(115),
    marginLeft: px2dp(12),
    borderRadius: px2dp(10),
  },

  infoContainer: {
    marginLeft: px2dp(11),
    flex: 1,
    height: px2dp(115),
  },
  title: {
    fontSize: px2dp(15),
    lineHeight: px2dp(21),
    color: "#000",
    paddingRight: px2dp(10),
  },
});

代码核心逻辑

  1. MasonryFlashList 自动慢速滚动动画,借鉴 这一篇瀑布流列表 自动滚动动画,在这里运用时 封装在useListViewAutoScrollAnimate之中

  2. 把列表变成水平滑动的方式是,将列表旋转90度,将Item内容反转90度。

为何不使用类似ScrollViewhorizontal属性,直接设成水平滚动不就好了?
我也想,只不过MasonryFlashList官方明确表示,不支持呀~

以下是列表垂直变水平的关键步骤

1
2
3
const itemWidth = px2dp(12 + 86.5 + 251.5);  //大值
const itemHeight = px2dp(139);               //小值
const itemSpace = px2dp(17);
  • Item内容,按蓝湖图设置真实宽高
1
2
3
4
transformContainer: {
    width: itemWidth,  //大
    height: itemHeight //小
}
  • Item 要被颠倒90度,展示在一个垂直列表里,所以transform这样设置
1
2
3
4
5
transform: [
      { rotate: "90deg" },
      { translateX: (itemWidth - itemHeight) / 2 },
      { translateY: (itemWidth - itemHeight) / 2 },
    ]
  • 在这个垂直列表里,每个Item的壳容器 宽高是这样的
1
2
3
4
container: {
    height: itemWidth, //大
    width: itemHeight, //小
}
  • 把垂直的列表变成 水平列表,那么对列表反向旋转90度,即这样设
1
2
3
4
5
scrollContainer: {
    width: itemHeight * 2 + itemSpace * 2, //px2dp(139 * 2 + 17),
    height: px2dp(375),
    transform: [{ rotate: "270deg" }],
  },