reactjs - 无法使用 @emotion/styled 访问样式组件中的主题

标签 reactjs typescript material-ui styled-components emotion

enter image description here
我正在使用 @emotion/react主题并将主题注入(inject)其中,我可以使用 useTheme 访问主题到组件中,但无法使用 @emotion/styled 将主题访问到样式中.请问有什么帮助吗?

//libs
import React from 'react';
import styled from '@emotion/styled';

import StylesProvider from '@mui/styles/StylesProvider';
import { ThemeProvider } from '@emotion/react';


const THEME = {
  primary: 'red'
}

const StyledText = styled('p')`
  color: ${({ theme }) => theme.primary};
`;

function App() {
  return (
    <StylesProvider injectFirst>
      <ThemeProvider theme={THEME}>
        <StyledText>test</StyledText>
      </ThemeProvider>
    </StylesProvider>
  );
}

export default App;



here is sample code

最佳答案

你需要这样称呼它。见 this部分了解更多详情。

const StyledTextField = styled('div')(({ theme }) => `
  margin: ${theme.spacing(1)};
  background-color: ${theme.palette.primary.main};
  /* ... */
`);
或者你也可以像在文档中一样使用 JS 对象:
const StyledTextField = styled('div')(({ theme }) => ({
  margin: theme.spacing(1),
  backgroundColor: theme.palette.primary.main,
  // ...
}));
Codesandbox Demo

关于reactjs - 无法使用 @emotion/styled 访问样式组件中的主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69718472/

相关文章:

javascript - 将多个对象聚合为一个数组并同步更改

angular - 引用外部 typescript 文件时如何避免 "Module not found: Error: Can' t resolve 'tslib' "-error?

javascript - 如何将一些过滤器与恢复初始对象一起使用?

reactjs - React - Material-UI Modal 导致 tabindex 错误

reactjs - 如何在 Material UI makestyles 中使用媒体查询

reactjs - 通过react-redux调度组件

reactjs - 是否可以在 React render 中编写 if/else 语句

node.js - 为什么 React 中的类无法正确加载?

javascript - 为什么当我使用 .map 而不是硬编码来动态填充内容时,Material UI 选项卡停止工作?

javascript - react Material UI 重置值