实现效果如图,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-native
apiAnimated.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端;