React使用styled-components如何向keyframes传递inicial、final自定义props
解决styled-components动态传参到keyframes的方案
你只需要将静态定义的keyframes和动画样式改造为可接收参数的函数,从组件props中读取inicial、final值动态生成动画即可,修改后的完整代码如下:
import { keyframes, css, styled } from 'styled-components' import React from 'react' // 将keyframes改造为接收初始、结束值的函数 const sliderzada = (inicial, final) => keyframes` from { transform: translate(${inicial}px) } to { transform: translate(${final}px) } `; // 将动画样式改造为接收props的函数,读取参数生成对应动画 const animation = (props) => css` animation: ${ sliderzada(props.inicial, props.final)} 1.2s ease-in-out; `; const Sliderzin = styled.div` ${props => props.isClicked && animation(props)} `; const Slider = () => { const [isClicked, setIsClicked] = React.useState(false) const [inicial, setInicial] = React.useState(0) const [final, setFinal] = React.useState(-1250) return ( <div className={styles.wrapper}> <Sliderzin inicial={inicial} final={final} isClicked={isClicked}> </Sliderzin> </div> ) }
原理解释
- 你之前的代码中keyframes是静态常量,定义时就已经固定了translate的位移值,无法接收组件传递的动态props
- 改为函数形式后,每次触发动画时都会基于当前传入的
inicial、final值生成对应的keyframes实例,实现动态位移的动画效果 - 组件侧的传参逻辑不需要做任何修改,已经满足参数传递要求
内容的提问来源于stack exchange,提问作者Anderson Souza
相关产品推荐
相关产品推荐

