【问题标题】:How to pass props to keyframes in styled-component with react?如何通过反应将道具传递给样式组件中的关键帧?
【发布时间】:2018-11-20 23:54:41
【问题描述】:

我有以下代码,我想将 y 的值从反应组件传递给 moveVertically 关键帧。有可能吗?

import React from 'react';
    import styled, {keyframes} from 'styled-components';


    const moveVertically = keyframes`
        0% {
            transform : translateY(0px) 
        }
        100% {
            transform : translateY(-1000px) //I need y here
        }
    `;

    //I can access y in here via props but can't send it above
    const BallAnimation = styled.g`
        animation : ${moveVertically} ${props => props.time}s linear
    `;


    export default function CannonBall(props) {

        const cannonBallStyle = {
            fill: '#777',
            stroke: '#444',
            strokeWidth: '2px',
        };

        return (
            <BallAnimation time = {4} y = {-1000}>
                <circle cx = {0} cy = {0} r="25" style = {cannonBallStyle}/>
            </BallAnimation>
        );
    }

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    这个使用打字稿的进度条动画示例

        export const animatedProgress = (y:number) => keyframes`
    0%{
          width: 0%;
        }
        25%{
            width:  ${y >= 25 ? 25 : y}%;
        }
        50%{
          width:  ${y >= 50 ? 50 : y}%;
        }
        75%{
          width:  ${y >= 75 ? 75 : y}%;
        }
        100%{
          width:  ${y >= 100 ? 100 : y}%;
        }
    
    `;
    
    export const ProgressAnimated = styled("div")<progressAnimated>`
    
    animation : ${props => animatedProgress(props.value)} 3s linear;
    `;
    

    【讨论】:

      【解决方案2】:

      你可以让 moveVertically 成为一个函数。请考虑以下代码:

      const moveVertically = (y) => keyframes`
          0% {
              transform : translateY(0px) 
          }
          100% {
              transform : translateY(${y}px)
          }
      `;
      
      const BallAnimation = styled.g`
          animation : ${props => moveVertically(props.y)} ${props => props.time}s linear
      `;
      

      这里有 yBallAnimation 的道具中。因此,您可以提取它并将其传递给 moveVertically 函数,该函数接受 y 值作为参数。

      【讨论】:

      • 这个答案对于新版本的样式组件并不实际,因为语法 `(y) => keyframes`` 是错误的
      • 这对我来说是一种魅力。那只是与 CSS 混合的 Javascript 新语法。但这仅在我添加 !important 以覆盖原始 CSS 动画时才有效。
      【解决方案3】:

      moveVertically 成为一个返回 关键帧 样式组件的函数怎么样?

      这样,你可以传入你想要的道具:

      const moveVertically = (y) =>
        keyframes`
          0% {
            transform: translateY(0px);
          }
          100% {
            transform: translateY(${y}px);
          }
        `
      
      const BallAnimation = styled.g`
        animation: ${props => moveVertically(props.y)} ${props => props.time}s linear;
      `
      

      【讨论】:

        猜你喜欢
        • 2019-11-08
        • 2017-08-17
        • 2019-04-27
        • 1970-01-01
        • 2022-06-19
        • 1970-01-01
        • 2020-07-28
        • 2019-07-29
        • 1970-01-01
        相关资源
        最近更新 更多