javascript - Styled-Components - 将道具/主题传递给关键帧?
问题描述
尝试一些带有样式组件和关键帧的东西。这是关于动画文本颜色的。它在使用十六进制代码或 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}
`;
解决方案
我想你可以从一个接受道具作为参数的函数中返回你的关键帧:
const getChangeColor = (props) => keyframes`
0% {
color: ${props.theme.color.somecolor};
}
100% {
color: ${props.theme.color.somecolor};
}
`;
...然后在调用时将道具传递给函数:
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;
`;
}}
`;
希望这可以帮助。
推荐阅读
- php - Laravel:419 会话在登录时过期,已经包含 CSRF 令牌和帖子
- bash - 我可以手动逐步执行bash,但不能在脚本中执行?
- mysql - 如何在 JOIN 表中使用 SQL CASE & COUNT
- python - 在 PCA 中使用超过 2 台 PC
- spring - 如何为Angular中的某些角色动态分配组件/字段权限?
- c# - 如何使用密钥从 KeyVault 获取凭据?
- azure-active-directory - Azure AD 和 Azure B2c
- superscript - 带有draw_label的ggplo2中的数学/上标注释
- javascript - Angular 事件窗口:滚动不触发(高级布局)
- javascript - 在循环 undefiend 中将数据保存到 mongoDB