【问题标题】:Passing props to material-ui button wrapped by styled-components with Typescript使用 Typescript 将 props 传递给由 styled-components 包装的 material-ui 按钮
【发布时间】:2021-10-13 02:49:03
【问题描述】:

我使用 typescript 模板创建了 react 项目,并使用 styled-components 库中的 styled 方法设置了 Material-ui Button 组件的样式,如下所示:

import React from 'react';
import styled from 'styled-components';
import Button, {ButtonProps} from "@material-ui/core/Button";

type StyledButtonProps = ButtonProps & { primary?: boolean }


const styledButton = styled(Button)`
  background-color: ${(props: StyledButtonProps) => props.primary ? "palevioletred" : "white"};
  box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
  padding: 7px 14px;

  &:hover {
    background-color: aqua;
  }

  & .MuiButton-label {
    color: #070303;
  }
` as React.ComponentType<StyledButtonProps>

export default styledButton;

我正在尝试传递确定颜色的主要布尔值。它通常可以工作,但是当我尝试使用如下所示的样式按钮时会出现警告消息:

<StyledButton primary={true}>Styled Buton</StyledButton>

警告信息是:

这是为什么呢?我怎样才能摆脱这个警告?

【问题讨论】:

    标签: css reactjs typescript material-ui styled-components


    【解决方案1】:

    Styled-components 尝试将 primary=true 传递给 DOM,但 DOM 只接受字符串值 primary="true"。因此,它会警告您将true 更改为"true",以便它可以成功呈现到DOM。

    如果我们将primary={true} 更改为primary="true",则主要属性将显示在 DOM 上,如下所示:


    但我认为您不希望 primary 被渲染到 DOM,所以

    使用 Transient 道具消除警告:

    美元符号 ($) 前缀有助于样式组件避免将该属性传递给 DOM。 Read this for details

    <StyledButton $primary={true}>Styled Buton</StyledButton>
    
    ...
    
    background-color: ${(props: StyledButtonProps) =>
        props.$primary ? "palevioletred" : "white"};
    ...
    

    这里是codesandbox for demo

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2020-03-02
      • 1970-01-01
      • 2021-05-19
      • 2019-02-18
      • 2017-12-21
      • 2020-06-28
      • 2018-04-15
      • 2020-05-14
      相关资源
      最近更新 更多