【问题标题】:How to theme components with Styled-Component and Material-UI如何使用 Styled-Component 和 Material-UI 对组件进行主题化
【发布时间】:2021-01-29 03:40:15
【问题描述】:

我已尝试完全按照此处记录的内容进行操作:

How to theme components with styled-components and Material-UI?

import React from "react";
import { withTheme } from "@material-ui/core/styles";
import styled from "styled-components";

const StyledDiv = withTheme(styled.div`
  background: ${props => props.theme.palette.primary.main};
  color: ${props => props.theme.palette.primary.contrastText};
`);
export default function App() {
  return (
    <StyledDiv>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </StyledDiv>
  );
}

但是,我没有像上面那样使用“标准”HTML 组件,而是尝试使用 Material-UI 按钮,但没有成功。有人可以帮我解决我做错了什么吗?

这就是我正在尝试的:

styles.ts

import styled from 'styled-components';
import { withTheme } from "@material-ui/core/styles";
import { Button } from '@material-ui/core';

export const StyledInnerSignInButton = withTheme(styled(Button)`
    margin: ${props => props.theme.spacing(3, 0, 2)};
`)

index.tsx

import { StyledInnerSignInButton } from './styles';

[...]

<StyledInnerSignInButton
    type="submit"
    fullWidth
    variant="contained"
    color="primary"
>
    Sign In
</StyledInnerSignInButton>

我被困在这里,仍然是 React 新手。非常感谢任何帮助!

【问题讨论】:

  • 您能否更具体地说明什么不起作用?您是否看到错误或应用到按钮的样式不符合您的预期。我试用了您的代码here,它看起来可以正常工作
  • 对不起,我的挣扎是有些主题没有被应用。我没有收到任何错误消息,它只是没有做任何事情。我的一个朋友告诉我,间距不是一个函数,但是我如何通过 styled-components 来操作它呢?
  • 你可以尝试使用 React 语法发送 here 的相同内容吗?
  • 哦,是react语法,只检查JS窗口而不是HTML窗口

标签: javascript reactjs material-ui styled-components


【解决方案1】:

我设法解决了我的问题。这是由于specificity。有两种方法可以缓解这种情况,一种是用 && 包裹新的组件样式,例如:

export const StyledInnerSignInButton = withTheme(styled(Button)`
    && { margin: ${props => props.theme.spacing(3, 0, 2)}; }
`)

或者通过操纵 CSS 注入顺序,如文档中的 here

在您的“主” index.tsx 文件中,您将这样设置您的代码:

import React from 'react';
import { render } from 'react-dom';
import { StylesProvider } from '@material-ui/core/styles';
import Home from './pages/Home';

render(
  <React.StrictMode>
    <StylesProvider injectFirst>
      {/* component name */}
      <Home />
    </StylesProvider>
  </React.StrictMode>,
  document.getElementById('root')
)

希望对和我有同样问题的人有所帮助。

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 2021-08-18
    • 2020-07-18
    • 2021-05-23
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 2021-07-17
    • 2019-11-18
    相关资源
    最近更新 更多