reactjs - 如何使用 React 将 props 传递给样式组件中的关键帧?

标签 reactjs styled-components

我有以下代码,我想将 y 的值从 React 组件传递到 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>
        );
    }

最佳答案

您可以将 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 的 props 中有 y。因此,您可以提取它并将其传递给接受 y 值作为参数的 moveVertically 函数。

关于reactjs - 如何使用 React 将 props 传递给样式组件中的关键帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50802681/

相关文章:

javascript - 从react调用javascript方法

reactjs - 如何为 React 类组件声明附加属性?

javascript - 如何将 Prop 传递给循环内的样式化组件

javascript - 无法将样式应用于 Reactjs 中的样式组件元素

javascript - styled-components 'css' 未定义 no-undef

reactjs - 在 Material UI 中使用样式组件应用单选按钮颜色?

reactjs - 无法读取未定义的 react 测试库的属性 'addListener'

javascript - 在 map 功能中获取图像尺寸?

javascript - 带有 react.js 的编译文件太大

css - 按钮在 iOS 上的定位与 Windows 和 Android 上的不同