首页 > 解决方案 > 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}
`;

标签: javascriptcssreactjscss-animationsstyled-components

解决方案


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

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

希望这可以帮助。


推荐阅读