import React, { useRef, useEffect, useState } from 'react' import './index.less' import styled from 'styled-components' interface TextScrollProps { /** * 持续时间/s */ duration: number, children: React.ReactElement, } function TextScroll(props: TextScrollProps) { const { duration, children } = props const defaultState = { contentWidth: 0, right: 0, duration, } const [state, setState] = useState(defaultState) let ref = useRef(null) useEffect(() => { const { offsetWidth, parentElement } = ref.current as HTMLParagraphElement setState({ ...state, contentWidth: offsetWidth, right: parentElement!.offsetWidth, }) }, []) const { contentWidth, right, duration: timing } = state const animationName = `marquee_${contentWidth}` console.log(11111, right, contentWidth); const Text = styled.div` position: relative; left: ${right}px; animation: ${animationName} ${timing}s linear infinite both; animation-play-state: running; animation-fill-mode: forwards; @keyframes ${animationName} { 0% { transform: translateX(0px); } 100% { transform: translateX(${contentWidth - right}px); } } ` return (
{children}
) } TextScroll.defaultProps = { content: '', duration: 3, } export default React.memo(TextScroll)