[英]How to pass props to keyframes in styled-component with react?
我有以下代码,我想将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>
);
}
您可以使 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
`;
在这里你有y在BallAnimation 的道具中。 因此,您可以提取它并将其传递给moveVertically函数,该函数接受 y 值作为参数。
如何使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;
`
此示例用于使用打字稿的进度条的动画
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;
`;
const Stick = styled("div")(() => ({
"@keyframes gradient": {
"0%": {
backgroundPosition: "0% 50%",
},
"50%": {
backgroundPosition: "100% 50%",
},
"100%": {
backgroundPosition: "0% 50%",
},
},
width: "40vw",
height: "20vw",
background:
"linear-gradient(-45deg, #ee7752, #e73c7e, #9581F4, #23a6d5, #23d5ab)",
animation: "gradient 10s ease infinite",
}));
我有以下代码,我想将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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.