【问题标题】:How to use Typography as a styled component in react of material UI如何在材质 UI 的反应中使用排版作为样式化组件
【发布时间】:2020-07-21 14:36:17
【问题描述】:

我是材质 UI 的新手。在这里,我正在尝试创建一个样式化的组件,它将是 Typography。所以,我尝试的是,

import styled from 'styled-components';


 import {
  FormGroup,
  FormControlLabel,
  Tooltip,
  FormControl,
  Select,
  Radio,
  Typography,
  Button
} from '@material-ui/core'
const StyledTypography = styled.Typography<Itest>(({ marginLeft, marginRight }) => ({
}))

但这给了我一个编译时错误。

Property 'Typography' does not exist on type 'ThemedStyledInterface<ThemeInterface>'

谁能帮我解决这个问题?

我使用了以下方式

const StyledTypography = styled(Typography)<ISortBySelector>(({ fontSize }) => ({
  && {
  fontFamily: 'Roboto',
  fontSize: fontSize ? fontSize : '10px',
  fontWeight: 'normal',
  fontStretch: 'normal',
  fontStyle: 'normal',
  lineHeight: 'normal',
  letterSpacing: fontSize ? '0.14px' : '0.07px',
  width: fontSize ? '50px' : '35px',
  height: fontSize ? '19px' : '14px',
  color: '#000000',
  cursor: 'pointer'
  }
}))

【问题讨论】:

  • 是的,我已经导入了你的意思是样式对吗?
  • @keikai 我已经导入了样式,但你说的我无法理解。
  • @keikai 我也更新了导入,请检查

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


【解决方案1】:

我不确定您是否使用了正确的语法,但这是我通常将组件传递给样式组件的方式(注意我没有使用点符号)。此外,您可以使用通常的 CSS 语法,而不是较低的驼峰格式。

import Typography from '@material-ui/core/Typography';
import styled from 'styled-components';

const StyledTypography = styled(Typography)<Itest>`
   && {
     font-family: Roboto;
     // customise your styles here
   }
`;

如果你想将其他 props 传递给StyledTypography,例如,将variant 设置为caption

<StyledTypography variant='caption'>
  Some text
</StyledTypography>

【讨论】:

  • 嘿,谢谢这个作品。我们可以将一件事作为 variant='caption' 传递给该组件吗?因为我想把它作为一个跨度所以
  • 当然可以!您可以将道具传递给 StyledTypography 组件。我已经更新了我的示例。让我知道它是否有效?
  • 这里只有一件事,我已经在样式化组件中为此添加了 css。但它仍然采用默认字体的样式,而不是我在样式组件中指定的样式。
  • 嗯...如果您使用 chrome devtools 或其他工具检查元素,然后选择该元素,它会显示什么?是 css 属性被覆盖还是什么?
  • 字体大小:14px;字体系列:Roboto;字体粗细:400;行高:1.43;字母间距:0.3px;这个属性被覆盖了
【解决方案2】:

我不认为使用点表示法是您的问题。我认为这就是你想要达到的目标:

import { styled } from '@mui/material/styles'
import Typography from '@mui/material/Typography'

export const StyledTypography = styled(Typography)(({ theme }) => ({
  '&': {
    color: theme.palette.common.black,
    // ...and so on
  },
})) as typeof Typography

如果您不使用主题中的变量,则另一个答案是可以的。另外,请注意,当前特定组件上的 component 属性存在错误,因此可能需要 as typeof Typography

【讨论】:

    猜你喜欢
    • 2018-10-08
    • 2020-09-13
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2021-04-21
    • 2019-02-02
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多