使用样式组件动画背景渐变

问题描述 投票:0回答:1

我将<Paper />(我使用Material-UI,v1.0.0-beta.25)的背景设​​置为渐变色。单击“添加”按钮并从颜色选择器中选择一个颜色,即可自动添加颜色。到这个时候,我的代码执行此操作:

enter image description here

我想动画组件的背景渐变来获得类似this的东西。使用笔的代码,删除一些我认为不必要的行并添加styled-components的实现,我写道:

import styled, { keyframes } from 'styled-components';

{/* rest of the code */}

render() {

  const gradient = keyframes`
    0% {
      background-position: 0% 50%
    }
    50% {
      background-position: 100% 50%
    }
    100% {
      background-position: 0% 50%
    }
  `;

  const MyPaper = styled(Paper)`
    && {
      background: ${ colors.length == 0 ? `linear-gradient(to right, ${ "#FFFFFF" }, ${ "#FFFFFF" })` 
        : `linear-gradient(to right, ${ colors.map((color, key) => color.name ) })` };

      animation: ${gradient} 15s ease infinite;
    }
  `;

  return (
    <div>
      <div className = { classes.root }>

        {/* Color selected */}
        <div>
          <MyPaper className = { classes.paperStyle } elevation = { 4 }></MyPaper>
        </div>
        <br /><br /><br />

        {/* rest of the code */}

但由于某种原因,背景没有动画。

我做错了什么,错过了什么,还是有其他方法可以做到这一点?我会感谢任何帮助,以实现我的目标。提前致谢!

css reactjs animation material-ui styled-components
1个回答
1
投票

除了你的数组colors的结构,我不确定它是否正确,你需要在CSS中为你的组件MyPaper定义一个大于100%和100%的背景大小值,以便动画工作。

@keyframes gradient {
    0% {
      background-position: 0% 50%;
    }
    50% {
      background-position: 100% 50%;
    }
    100% {
      background-position: 0% 50%;
    }
}

.gradient {
 height: 100px;
 width: 100px;
 background: linear-gradient(to right, red, yellow, blue);
 background-size: 110% 110%;
 animation: gradient 15s ease infinite;
}

.cool {
 background: linear-gradient(to right, green, red, black);
 background-size: 200% 200%;
}
<div class="gradient"></div>
<div class="gradient cool"></div>

也许您可能需要为材质的Paper组件设置尺寸(高度和宽度),以使其也能正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.