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