React 和 Material-UI:使用 TypeScript 在 createStyles() 中未定义主题

2024-01-02

我正在学习 React with TypeScript 并使用 Material UI 框架作为前端。我尝试让媒体查询正常工作,但出现错误:

未捕获的类型错误:无法读取未定义的属性“up” 在样式(webpack-internal:///./app/components/navigation/Toolbar/index.tsx:59)

这是对应的代码:

const styles = ({breakpoints}: Theme) => createStyles( {
    grow: {
        flexGrow: 1
    },
    menuButton: {
        marginLeft: -12,
        marginRight: 20
    },
    sectionDesktop: {
        display: 'none',
        [breakpoints.up('md')]: {
            display: 'flex'
        }
    },
    sectionMobile: {
        display: 'flex'
    },
})

样式通过以下方式传递给组件:

export default withStyles(styles)(Toolbar)

我读到不需要创建自定义主题,因为默认主题将自动传递给函数。但是,主题的断点属性未定义,这会导致空白页。

感谢您的帮助

Edit

这是在没有任何其他组件的情况下仍然会产生问题的组件的代码。

import * as React from 'react'
import {
    Theme
} from '@material-ui/core'
import {
    createStyles,
    WithStyles,
    withStyles
} from '@material-ui/styles'
// import Drawer from '../Drawer'

const styles = ({breakpoints}: Theme) => createStyles( {
    grow: {
        flexGrow: 1
    },
    menuButton: {
        marginLeft: -12,
        marginRight: 20
    },
    sectionDesktop: {
        display: 'none',
        [breakpoints.up('md')]: {
            display: 'flex'
        }
    },
    sectionMobile: {
        display: 'flex'
    },
})

namespace Toolbar {
    interface Props {
    }

    export interface State {
        isOpen : boolean
        mobileMoreAnchorEl? : EventTarget & HTMLElement
    }

    export type AllProps = Props & WithStyles<typeof styles>
}

class Toolbar extends React.Component<Toolbar.AllProps, Toolbar.State> {
    constructor(props: Toolbar.AllProps, context?: any) {
        super(props, context);
        this.state = { isOpen: false, mobileMoreAnchorEl: undefined}
    }

    render() {
        const { classes } = this.props
        // const { isOpen } = this.state

        return(
            <React.Fragment>
                <div className={classes.sectionDesktop}>
                    Hello
                </div>
                <div className={classes.sectionMobile}>
                    World
                </div>
            </React.Fragment>
        )
    }

}

export default withStyles(styles)(Toolbar)

main.tsx(又名index.js)如下所示:

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import { configureStore } from 'app/store';
import { Router } from 'react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { App } from './app';

// prepare store
const history = createBrowserHistory()
const store = configureStore()
const theme = createMuiTheme()

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <MuiThemeProvider theme={theme} >
        <App />
      </MuiThemeProvider>
    </Router>
  </Provider>,
  document.getElementById('root')
);

因此,添加 MuiThemeProvider 没有帮助。


UPDATE

在第一次写这个答案的时候,@material-ui/styles不稳定。它不再是(从 v4 开始),但通常最好还是从@material-ui/core/styles因为从以下位置导入时默认主题将不可用@material-ui/styles.


你可以阅读here https://material-ui.com/css-in-js/basics/ that @material-ui/styles不稳定(alpha 版本)。

您会在我的 CodeSandbox 中注意到我正在使用:

import { withStyles, createStyles } from "@material-ui/core/styles";

而不是从导入这些@material-ui/styles。当我使用与您相同的导入时,我能够重现您的问题。


v5 更新

在 v5 中,使用makeStyles and withStyles已被弃用,并且它们已从@material-ui/core并且只能通过以下方式访问@material-ui/styles。在 v5 中,makeStyles and withStyles除非您通过以下方式提供访问权限,否则无权访问该主题ThemeProvider(为此,您应该使用两者的最新 v5 版本@material-ui/core and @material-ui/styles)。下面是一个有效的 v5 示例。

import React from "react";
import ReactDOM from "react-dom";
import { createTheme, ThemeProvider } from "@material-ui/core/styles";
import { withStyles } from "@material-ui/styles";
const styles = ({ breakpoints }) => ({
  grow: {
    flexGrow: 1
  },
  menuButton: {
    marginLeft: -12,
    marginRight: 20
  },
  sectionDesktop: {
    display: "none",
    [breakpoints.up("md")]: {
      display: "flex"
    }
  },
  sectionMobile: {
    display: "flex"
  }
});
const MyToolbar = (props) => {
  return (
    <>
      <div className={props.classes.sectionDesktop}>Section Desktop</div>
      {props.children}
      <div className={props.classes.sectionMobile}>Section Mobile</div>
    </>
  );
};
const theme = createTheme();
const StyledToolbar = withStyles(styles)(MyToolbar);
function App() {
  return (
    <ThemeProvider theme={theme}>
      <StyledToolbar>
        <div>Hello</div>
        <div>CodeSandbox</div>
      </StyledToolbar>
    </ThemeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 和 Material-UI:使用 TypeScript 在 createStyles() 中未定义主题 的相关文章

  • 无法获取子 DOM 元素

    注 由于问题有点复杂 为了可读性对代码进行了抽象 We ve a
  • React Native 中循环 Json 并显示

    How do I go about looping the result i retrieved from Json render function console log this state list contents
  • SWC with JavaScript:如何处理 CSS 导入以及如何绝对导入?

    TL DR 如何告诉 SWC 编译 React 组件中导入的 CSS 文件 如何告诉 SWC 在测试和 React 组件中编译绝对导入 这是一个最小的可重现示例 https github com janhesters riteway swc
  • React:在哪里扩展对象原型

    我使用创建了一个纯 React 应用程序创建反应应用程序 https github com facebookincubator create react app 我想延长String类并在一个或多个组件中使用它 例如 String prot
  • 通过 Javascript 填充 ReactJS HTML 表单

    我正在开发一个应用程序 在打开第 3 方网站后 我可以在浏览器上下文中运行我自己的 Javascript 作为一个基于reactjs构建并具有登录表单的示例网站 您可以参考此链接 我正在尝试在reactjs生成的表单中填写用户名和密码 但是
  • 嵌套对象的 setState

    我有一个嵌套对象作为状态 并且在组件中有一个表单 我正在考虑每次用户在表单中输入某些内容时更新状态 并且为了避免为每个输入创建许多函数 我正在考虑使用 switch 创建单个函数 使用 switch 创建单一函数是个好主意吗 如何更新对象的
  • Redux 状态 - 最大推荐大小

    我正在构建一个项目管理应用程序 但我仍然在努力解决一个问题 在 Redux 状态中存储什么以及 按需 加载什么 Redux 状态是否有已知的 最大推荐大小 几十千字节 几百千字节 兆字节单位 请记住 归根结底 Redux 只是 如何 将信息
  • Typescript 从 CDN 导入 .js

    在我的 ts 文件中 我想引用 js 由第三方托管 并使用 js 文件中的一些函数 到目前为止 我发现如何做到这一点的唯一方法是修改 html 页面并插入 ts 本身的标签 除了修改 html 页面之外 还有其他更优雅的方法吗 听起来您正在
  • 类型“QueryFn”中不存在“查询”|角火2

    类型参数 query limitTolast number orderByKey 布尔值 不可分配给 QueryFn 类型的参数 对象文字只能指定已知属性 并且 QueryFn 类型中不存在 query 包 json angularfire
  • React 中的输入仅允许数字(antd 样式)

    我知道 type number 有效 但这不是我想要的 my HTML
  • 如何在反应中循环

    如何循环重复 这是我的代码 这是App js import React from react import App css import Child from Child Child function App return div div
  • React 文件预览 (FIREBASE)

    我目前将文件存储在 Firebase 存储中 我希望能够实时生成每个文件的文件预览 映射 例如 PDF 文件会将第一页显示为图像 docx 将是文档的第一页 pptx 将是第一张幻灯片 未知文档将是默认文档符号 有人知道有什么好的服务可以轻
  • `navigator.geolocation.getCurrentPosition()` 在 iOS PWA 上挂起

    我有这个片段 const getCurrentPosition gt new Promise
  • Firebase 托管部署失败

    Running firebase deploy在给我一个超时错误之前会运行几分钟Error ESOCKETTIMEDOUT 我之前已经成功部署了多次 除了项目的前端 用 React 编写 之外 没有更改任何内容 我有一个单独的文件夹 其中包
  • 如何在 TypeScript 中定义具有动态属性的对象的类型

    我有一个对象title作为字符串和orderas number 那么上面就会有动态数量的number类型的属性 所以我尝试像下面这样定义它 appraisalGroups Array lt title string order number
  • React js Stripe 结账不起作用

    我正在尝试在 React js 应用程序中呈现条带结账默认表单
  • 在 React 中实现 Google 登录错误 -

    我正在尝试在 React 中实现 google 登录 这是我的组件 import Fragment useEffect from react import GOOGLE CLIENT ID from some file const Goog
  • Angular 2获取元素高度

    我这里有一个非常简单的例子 它只是一个带有单个 div 的角度应用程序 是否可以获取div的角度高度 我想我可以用 ViewChild 和 offsetHeight 来做到这一点 import Component ElementRef Vi
  • 问题:为什么React Native Video不能全屏播放视频?

    我正在react native 0 57 7 中为android和ios创建一个应用程序并使用反应本机视频 https github com react native community react native video播放上传到的视频
  • 如何在 Swiper 实例之外使用 useSwiper?

    我在用着用于 React 的滑动器 https swiperjs com react显示一些幻灯片 我一直坚持使用外部按钮在幻灯片 上一张和下一张 之间导航 刷卡器有一个useSwiper hook https swiperjs com r

随机推荐