【问题标题】:styled-components conditional props doesn't work in Material-ui componentsstyled-components 条件道具在 Material-ui 组件中不起作用
【发布时间】:2020-03-28 19:43:35
【问题描述】:

我想使用 Material-UI 和 styled-components 在 Grid 组件上设置淡入淡出动画。但它不起作用,并且条件道具存在错误。请告诉我该怎么做?

import React from "react";
import styled, { keyframes } from "styled-components";
import { Grid } from "@material-ui/core";

const fadeIn = keyframes`
  0% {
    height: 0
  }
  50% {
    height: 50%;
  }
  100% {
    height: 100%;
  }
`;

const fadeOut = keyframes`
  0% {
    height: 100%
  }
  50% {
    height: 50%;
  }
  100% {
    height: 0;
  }
`;


const AnimationGrid = styled(Grid)<{ isOpen: boolean }>`
  && {
    visibility: ${props => (props.isOpen ? "visible" : "hidden")};
    animation: ${props => (props.isOpen ? fadeIn : fadeOut)}
      0.3s linear 0s 1 forwards;
  }
`;


type AnimationProps = {
  isOpen: boolean;
};


const AnimationComp = ({isOpen}: AnimationProps) => {
  return (
        <AnimationGrid container isOpen={isOpen}>
          <Grid item xs={6}>
              Here is left section 
          </Grid>
          <Grid item xs={6}>
              Here is right section
          </Grid>
        </AnimationGrid>
  )
}

控制台也有错误。淡入动画很好,但淡出不起作用。

Warning: React does not recognize the `isOpen` prop on a DOM element. 
If you intentionally want it to appear in the DOM as a custom attribute, 
spell it as lowercase `isopen` instead. If you accidentally passed it from a parent component, 
remove it from the DOM element.

我会说 isOpen 道具效果不佳。谢谢。

【问题讨论】:

标签: reactjs material-ui styled-components


【解决方案1】:

你的问题由两部分组成,所以我会这样回答。

对于控制台错误:这种行为一直困扰着很多人。您看到此错误的原因是属性 isOpen 已传递给底层 DOM 元素。但是,DOM 元素不支持布尔属性isOpen。 要解决此问题,您可以使用

styled(({ isOpen, ...props }) => <Grid {...props} />)<{ isOpen: boolean }>`...`

对于动画部分:你看不到淡出动画,因为你在它的开头设置了visibility: hidden。这样,元素立即消失。要获得与visibility: hidden 类似的行为, 你可以将opacity: 0添加到你的动画中'100%' 并设置pointer-events: ${props =&gt; props.isOpen ? 'initial' : 'none'}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 2019-06-27
    • 2018-08-09
    • 2021-05-19
    • 2018-05-29
    • 2020-05-06
    • 1970-01-01
    • 2018-06-19
    相关资源
    最近更新 更多