如何为自定义Loader组件添加波浪加载动画效果
为自定义Loader组件添加波浪加载动画效果
我已经开发了一个用作加载器(Loader)的自定义组件Item,希望为其添加波浪状的加载动画效果,以下是该组件的代码及效果示意图:
export const Item = (props) =>{ const {height, width, bgColor, br} = props return( <View style={styles.item(height, width, bgColor, br)}></View> ) }

解决方案(React Native 版本)
利用 React Native 的 Animated API 实现无限循环的波浪流动效果,代码如下:
import React, { useEffect, useRef } from 'react'; import { View, Animated, Easing } from 'react-native'; export const Item = (props) => { const { height, width, bgColor, br = 8 } = props; const waveTranslateX = useRef(new Animated.Value(0)).current; const waveOpacity = useRef(new Animated.Value(0.3)).current; useEffect(() => { Animated.loop( Animated.sequence([ Animated.parallel([ Animated.timing(waveTranslateX, { toValue: width, duration: 1500, easing: Easing.linear, useNativeDriver: true, }), Animated.timing(waveOpacity, { toValue: 0.6, duration: 750, easing: Easing.inOut(Easing.ease), useNativeDriver: true, }), ]), Animated.parallel([ Animated.timing(waveTranslateX, { toValue: 0, duration: 1500, easing: Easing.linear, useNativeDriver: true, }), Animated.timing(waveOpacity, { toValue: 0.3, duration: 750, easing: Easing.inOut(Easing.ease), useNativeDriver: true, }), ]), ]) ).start(); }, [width]); const styles = { item: (h, w, bg, borderRadius) => ({ height: h, width: w, backgroundColor: bg, borderRadius: borderRadius, overflow: 'hidden', position: 'relative', }), waveLayer: { position: 'absolute', inset: 0, overflow: 'hidden', }, wave: { position: 'absolute', top: 0, left: -width, width: width * 2, height: '100%', backgroundColor: 'rgba(255,255,255,0.4)', borderRadius: '50%', transform: [{ translateX: waveTranslateX }], opacity: waveOpacity, }, }; return ( <View style={styles.item(height, width, bgColor, br)}> <Animated.View style={styles.waveLayer}> <Animated.View style={styles.wave} /> </Animated.View> </View> ); };
实现说明:
- 外层容器保留原组件样式,设置
overflow: hidden裁剪波浪超出部分 - 通过
Animated.loop实现波浪的循环平移和透明度变化,模拟流动效果 - 波浪层使用两倍宽度的圆角矩形,横向平移时形成连续的波浪扫过视觉
解决方案(Web React 版本)
如果是 Web 端组件,可通过 CSS 动画快速实现:
import React from 'react'; import styled from 'styled-components'; const ItemContainer = styled.div` height: ${props => props.height}px; width: ${props => props.width}px; background-color: ${props => props.bgColor}; border-radius: ${props => props.br}px; overflow: hidden; position: relative; &::after { content: ''; position: absolute; top: 0; left: -100%; width: 200%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent); animation: wave 1.5s infinite linear; } @keyframes wave { 0% { left: -100%; } 100% { left: 100%; } } `; export const Item = (props) => { const {height, width, bgColor, br = 8} = props; return( <ItemContainer height={height} width={width} bgColor={bgColor} br={br} /> ) }
实现说明:
- 利用伪元素创建渐变波浪层,通过 CSS
@keyframes控制横向位移 - 渐变采用透明-半透明-透明的过渡,模拟波浪的通透流动感
内容的提问来源于stack exchange,提问作者sam
相关产品推荐
相关产品推荐

