gpt4 book ai didi

javascript - Styled-Components - 将 Prop /主题传递给关键帧?

转载 作者:行者123 更新时间:2023-12-05 08:22:36 26 4
gpt4 key购买 nike

尝试一些带有样式组件和关键帧的东西。这是关于动画文本颜色。它在使用十六进制代码或 css 颜色名称时确实有效。但是,我想使用我在主题中定义的颜色。不过好像不行?我如何在这里使用 Prop ?

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}
`;

最佳答案

我想你可以从一个接受 Prop 作为参数的函数中返回你的关键帧:

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;
`;
}}
`;

希望这对您有所帮助。

关于javascript - Styled-Components - 将 Prop /主题传递给关键帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com