[英]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.