[英]Styled-Components - Pass Props / Theme to keyframes?
尝试一些带有样式组件和关键帧的东西。 这是关于动画文本颜色。 它在使用十六进制代码或 css 颜色名称时确实有效。 但是,我想使用我在主题中定义的颜色。 不过好像没用? 我如何在这里使用道具?
const changeColor = keyframes`
0% {
color: ${props => props.theme.color.somecolor};
}
100% {
color: ${props => props.theme.color.somecolor};
}
`;
const ColorChange = css`
-webkit-animation: ${changeColor} 3s infinite;
-moz-animation: ${changeColor} 3s infinite;
-o-animation: ${changeColor} 3s infinite;
-ms-animation: ${changeColor} 3s infinite;
animation: ${changeColor} 3s infinite;
`;
const ColorChangeComponent = styled.span`
${ColorChange}
`;
我想你可以从一个接受 props 作为参数的函数返回你的关键帧:
const getChangeColor = (props) => keyframes`
0% {
color: ${props.theme.color.somecolor};
}
100% {
color: ${props.theme.color.somecolor};
}
`;
...然后在调用函数时将 props 传递给函数:
const ColorChange = css`
-webkit-animation: ${props => getChangeColor(props)} 3s infinite;
-moz-animation: ${props => getChangeColor(props)} 3s infinite;
-o-animation: ${props => getChangeColor(props)} 3s infinite;
-ms-animation: ${props => getChangeColor(props)} 3s infinite;
animation: ${props => getChangeColor(props)} 3s infinite;
`;
...或简化:
const ColorChange = css`
-webkit-animation: ${getChangeColor} 3s infinite;
-moz-animation: ${getChangeColor} 3s infinite;
-o-animation: ${getChangeColor} 3s infinite;
-ms-animation: ${getChangeColor} 3s infinite;
animation: ${getChangeColor} 3s infinite;
`;
...或者甚至可以减少函数调用的次数:
const ColorChange = css`
${props => {
const changeColor = getChangeColor(props);
return `
-webkit-animation: ${changeColor} 3s infinite;
-moz-animation: ${changeColor} 3s infinite;
-o-animation: ${changeColor} 3s infinite;
-ms-animation: ${changeColor} 3s infinite;
animation: ${changeColor} 3s infinite;
`;
}}
`;
希望这可以帮助。
我自己想通了。 问题是我没有将props
传递给keyframes
,而且我确实尝试像这样访问 props: ${props => props.theme.brandColorOne};
但是,在这种情况下,它应该像这样访问: ${props.theme.brandColorOne};
这是一个最小的例子(取自here) :
import styled from 'styled-components';
import { keyframes } from 'styled-components';
const colorize = props => keyframes`
0% {
background-color: ${props.theme.brandColorOne};
}
100% {
background-color: ${props.theme.brandColorTwo};
}
`;
const Wrapper = styled.div`
animation: ${colorize} 4s ease-in-out infinite;
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.