引入插件 react-transition-group
import { CSSTransition, TransitionGroup } from 'react-transition-group'
class TextAnimation extends Component { state = { data: [] } componentDidMount(){ this.setState({ data: this.props.str.split('') }) } render() { const { timeout, interval, showBox, exit_callback, start } = this.props const delay = interval || 400 return ( <div style={{ ...this.props.style }} className={Css.text_animation} ref={ref => (this.ref = ref)} > <TransitionGroup className={Css.text_list}> {this.state.data.map((val, index) => { return ( <CSSTransition key={index} in={start} timeout={200} onEnter={e => { // e.style.backgroundPositionY = `0` e.style.backgroundPositionY = `${utils.px2rem((+45 + 30) * 9+16)}` //图片默认位置 }} unmountOnExit onExited={exit_callback} //整个动画结束 onEntering={ e => { // // e.style.backgroundPositionY = `${-3 * val - 30}rem` e.style.backgroundPositionY = `${utils.px2rem((-45- 32 ) * val)}` //图片高45,2个数字间距32 // e.style.backgroundPositionY = `${utils.px2rem((0 ) * val)}` //图片高45,2个数字间距32 e.style.transitionProperty = "background-position-y" e.style.transitionDuration = `${(index + 1) * delay}ms` e.style.transitionTimingFunction = "ease-out" } } > <span key={index} /> </CSSTransition> ) })} </TransitionGroup> </div> ) } } export default TextAnimation
对应样式文件
.text_animation { height: 100%; .text_list { height: 100%; } span { px2rem(82px); height: px2rem(88px); display: inline-block; background-image: url("../../../../img/insurance/text_animation.png"); background-repeat: repeat-y; background-position: center 0; background-size: px2rem(28px) px2rem(770px); padding-right: px2rem(10px); position: relative; top: px2rem(4px); } }
然后引入即可
最后是需要一张如下一张透明的的图片:选择可以选中,转载自 :https://juejin.cn/post/6844903845965856782