样式组件的 'styled.div' 和 'keyframes' 有什么区别?
What is the difference between 'styled.div' and 'keyframes' for styled components?
我目前遇到 'keyframes' 样式组件的问题。我已经了解如何在 'styled.div' 中使用 props,但我无法在 'keyframes' 组件中使用 props。
我知道下面的例子有点基础,但它明白了我要表达的意思。这里的 'keyframes' 版本有什么问题:
const HomePageDiv = styled.div`
background: ${(props) => `red`};
`;
const backgroundChange = keyframes`
0%{
background: ${(props) => `blue`};
}
`;
这里的'styled.div'组件会呈现红色背景,但如果我包含关键帧动画,它会被完全忽略。另一方面,如果我要包含以下关键帧动画:
const backgroundChange = keyframes`
0%{
background: blue;
}
`;
我会从蓝色到红色完美淡化。这让我相信 'keyframes' 和 'styled.div' 组件在 props 用法上有不同的语法。有人可以帮我理解其中的区别吗?
要访问关键帧中的道具,您需要将 keyframe
道具传递给您的组件。
工作示例:
const rotate = keyframes`
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(${props => props.rotation || '360deg'});
}
`
const RotatingBox = styled.div`
animation: ${rotate} 10s linear infinite;
`
// Usage:
<RotatingBox rotation="180deg" />
此 "issue" 在工单 397 中突出显示
我终于找到了解决问题的方法。 Matthew Barbara 的解决方案对我不起作用,我不确定为什么,但我确实在 ticket 397.
中找到了解决方案
这就是我将解决方案应用到我自己的代码中的方式:
import styled, {keyframes} from 'styled-components';
const backgroundChange = (props) => keyframes`
0%{
background: ${props.color1};
}
`;
const HomePageDiv = styled.div`
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
position: absolute;
overflow: hidden;
animation: ${backgroundChange} 2s linear forwards 1;
`;
export default HomePageDiv;
这会将道具正确地传递到关键帧中,需要 ${} 的标准符号才能使用这些道具。这些道具必须通过你的组件传递,当然关键帧变量名也必须传递到你的动画中。
我目前遇到 'keyframes' 样式组件的问题。我已经了解如何在 'styled.div' 中使用 props,但我无法在 'keyframes' 组件中使用 props。
我知道下面的例子有点基础,但它明白了我要表达的意思。这里的 'keyframes' 版本有什么问题:
const HomePageDiv = styled.div`
background: ${(props) => `red`};
`;
const backgroundChange = keyframes`
0%{
background: ${(props) => `blue`};
}
`;
这里的'styled.div'组件会呈现红色背景,但如果我包含关键帧动画,它会被完全忽略。另一方面,如果我要包含以下关键帧动画:
const backgroundChange = keyframes`
0%{
background: blue;
}
`;
我会从蓝色到红色完美淡化。这让我相信 'keyframes' 和 'styled.div' 组件在 props 用法上有不同的语法。有人可以帮我理解其中的区别吗?
要访问关键帧中的道具,您需要将 keyframe
道具传递给您的组件。
工作示例:
const rotate = keyframes`
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(${props => props.rotation || '360deg'});
}
`
const RotatingBox = styled.div`
animation: ${rotate} 10s linear infinite;
`
// Usage:
<RotatingBox rotation="180deg" />
此 "issue" 在工单 397 中突出显示
我终于找到了解决问题的方法。 Matthew Barbara 的解决方案对我不起作用,我不确定为什么,但我确实在 ticket 397.
中找到了解决方案这就是我将解决方案应用到我自己的代码中的方式:
import styled, {keyframes} from 'styled-components';
const backgroundChange = (props) => keyframes`
0%{
background: ${props.color1};
}
`;
const HomePageDiv = styled.div`
height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
position: absolute;
overflow: hidden;
animation: ${backgroundChange} 2s linear forwards 1;
`;
export default HomePageDiv;
这会将道具正确地传递到关键帧中,需要 ${} 的标准符号才能使用这些道具。这些道具必须通过你的组件传递,当然关键帧变量名也必须传递到你的动画中。