【问题标题】:What is the difference between 'styled.div' and 'keyframes' for styled components?样式组件的“styled.div”和“关键帧”有什么区别?
【发布时间】:2018-11-18 12:56:59
【问题描述】:

我目前遇到样式组件的“关键帧”问题。我已经了解如何在“styled.div”中使用道具,但我无法在“关键帧”组件中使用道具。

我知道下面的例子有点基本,但它传达了我想要表达的意思。这里的“关键帧”版本有什么问题:

const HomePageDiv = styled.div`
    background: ${(props) => `red`};
`;

const backgroundChange = keyframes`
    0%{
        background: ${(props) => `blue`};
    }
`;

这里的 'styled.div' 组件将呈现红色背景,但如果我包含关键帧动画,它会被完全忽略。另一方面,如果我要包含以下关键帧动画:

const backgroundChange = keyframes`
    0%{
        background: blue;
    }
`;

我会完美地从蓝色变为红色。这让我相信'keyframes' 和'styled.div' 组件对于道具的使用有不同的语法。有人可以帮我理解其中的区别吗?

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    要访问关键帧中的道具,您需要将 keyframe 道具传递给您的组件。

    工作示例:

    const rotate = keyframes`
      0% {
        transform: rotate(0deg);
      }
    
      100% {
        transform: rotate(${props => props.rotation || '360deg'});
      }
    `
    
    const RotatingBox = styled.div`
      animation: ${rotate} 10s linear infinite;
    `
    
    // Usage:
    
    <RotatingBox rotation="180deg" />
    

    这个“问题”在工单397 中突出显示

    【讨论】:

      【解决方案2】:

      我终于找到了解决问题的方法。 Matthew Barbara 的解决方案对我不起作用,我不知道为什么,但我确实在票证 397 中找到了解决方案。

      这就是我将解决方案应用于我自己的代码的方式:

      import styled, {keyframes} from 'styled-components';
      
      const backgroundChange = (props) => keyframes`
          0%{
              background: ${props.color1};
          }
      `;
      
      const HomePageDiv = styled.div`
          height: 100vh;
          width: 100vw;
          display: flex;
          flex-direction: column;
          position: absolute;
          overflow: hidden;
          animation: ${backgroundChange} 2s linear forwards 1;
      `;
      
      export default HomePageDiv;
      

      这将正确地将道具传递到关键帧中,使用这些道具将需要 ${} 的标准符号。这些道具必须通过你的组件传递,当然关键帧变量名也必须传递到你的动画中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-05
        • 2014-05-26
        • 2015-07-28
        • 2010-09-28
        • 2017-12-16
        • 2022-12-22
        • 1970-01-01
        相关资源
        最近更新 更多