react native

80行代码实现react-native无缝滚动组件兼容web端

2019-05-22  本文已影响0人  lvzhiyi

实现效果如图,gif录制有点卡顿,实际效果要好很多

gif1.gif

数据展示型组件重要的是在于实现思想

要实现无缝滚动必定要将滚动自元素复制一份,从而衔接滚动的头部与尾部;这里主要用到React.cloneElement(child, props)React.Children.forEach()两个api,将需要渲染的子元素劫持,复制一份后渲染,并加上对应的key值:

React.Children.forEach(this.props.children, (child: React.ReactElement<any>, index) => {
      let newProps = {
            key: `${this.key}${index}flag`,
            ...child.props
      };
      this.arr.push(React.cloneElement(child, newProps));
});

此时得到了“双份”的children,当children滚动了“一份”children位置的时候将动画重新执行;从而造成视觉上的无缝滚动;滚动动画控制主要用到了react-nativeapiAnimated.timing:

        Animated.timing(this.animation, {
            toValue: meter,                                           // 动画终点值
            duration: this.props.scrolltime || 5000, 
            easing: Easing.linear,
        }).start(() => {
            this.animation = new Animated.Value(0);    // 重置动画初始值
        });

react-native持续动画的必要优化:呼叫原生动画驱动 + transform(translate):

        Animated.timing(this.animation, {
            toValue: meter,                                           
            duration: this.props.scrolltime || 5000, 
            easing: Easing.linear,
            useNativeDriver: true                        // 启用原生动画驱动
        })
        ……
        <Animated.View style={[{
              transform: {translateX: this.animation}    // transform(translate)控制动画位置
          }, styles]}>
                {newChildren}
        </Animated.View>

由于Animated库同时支持web端,只需将Animated.View 替换为 Animated.div 即可兼容到web端;

源码详见 https://github.com/lvzhiyi/react-naitve-SeamlessScroll,记得留下小心心(star);

上一篇下一篇

猜你喜欢

热点阅读