如何通过反应将道具传递给样式组件中的关键帧?

时间:2018-06-11 16:55:33

标签: reactjs styled-components

我有以下代码,我想将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>
        );
    }

3 个答案:

答案 0 :(得分:4)

你可以使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
`;

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

答案 1 :(得分: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;
`

答案 2 :(得分:-1)

example:

import styled, { css, keyframes } from 'styled-components';

const perc = 30

<AnimatedBar perc={perc} />


const AnimatedBar = styled.div`
  height: 10px;
  background-color: #831640;
  width: ${({ perc }) => !perc ? '0px' : `${perc}%`};
  animation: ${({ perc }) => css`${animation(perc)} 1s ease-in-out`};
  // in new version css` ` is required
`

const animation = (perc) => keyframes`
  from {
    width: 0px;
  }
  to {
    width: ${perc}%;
  }
`;