样式组件-将道具/主题传递给关键帧?

时间:2020-01-28 15:57:52

标签: javascript css reactjs css-animations 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}
`;

2 个答案:

答案 0 :(得分:5)

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

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

希望这会有所帮助。

答案 1 :(得分:0)

我自己弄清楚了。问题是我没有将props传递给keyframes,而且我也尝试像这样访问道具:${props => props.theme.brandColorOne};,但是应该这样访问:${props.theme.brandColorOne};

这是一个最小的示例(taken from 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;
`;