【问题标题】:ReactJS Material UI Typescript - withStyles warningReactJS Material UI Typescript - withStyles 警告
【发布时间】:2020-06-21 05:44:58
【问题描述】:

我不断收到此警告,尽管我的样式已按我的意愿应用:

道具类型失败:提供了 function 类型的无效道具 function
WithStyles(App),预计object
在 WithStyles(App) 中

import React from "react";
import {
  CssBaseline,
  Theme,
  createStyles,
  Paper,
  Typography,
  withStyles,
  WithStyles,
  withTheme
} from "@material-ui/core";

const styles = (theme: Theme) =>
  createStyles({
    layout: {
      width: "800",
      marginLeft: theme.spacing(2),
      marginRight: theme.spacing(2),
      [theme.breakpoints.up(800 + theme.spacing(2) * 2)]: {
        width: 800,
        marginLeft: "auto",
        marginRight: "auto"
      }
    },
    paper: {
      marginTop: theme.spacing(3),
      marginBottom: theme.spacing(3),
      padding: theme.spacing(2),
      [theme.breakpoints.up(800 + theme.spacing(3) * 2)]: {
        marginTop: theme.spacing(6),
        marginBottom: theme.spacing(6),
        padding: theme.spacing(3)
      }
    }
  });

interface AppProps extends WithStyles<typeof styles> {
  classes: any;
}

class App extends React.Component<AppProps> {
  constructor(props: AppProps) {
    super(props);
  }

  static defaultProps = {
    classes: styles
  };

  render() {
    return (
      <React.Fragment>
        <CssBaseline />

        <main className={this.props.classes.layout}>
          <Paper className={this.props.classes.paper}>
            <Typography component="h1" variant="h4" align="center">
              Sub Head
            </Typography>
            Hello World
          </Paper>
        </main>
      </React.Fragment>
    );
  }
}

export default withTheme(withStyles(styles)(App));

【问题讨论】:

    标签: html css reactjs typescript material-ui


    【解决方案1】:

    props接口扩展参考官方document

    import {
      WithStyles,
      withStyles,
      withTheme
    } from '@material-ui/core';
    
    interface Props extends WithStyles<typeof styles> {
      classes: any,
      ...
    }
    
    class YourComponent extends React.Component<Props, State>{
      ...
    }
    
    export default withTheme(withStyles(styles)(YourComponent));
    

    更新

    你不需要从样式中设置默认道具

      static defaultProps = {
        classes: {},
      }
    

    会好的。猜测错误来自这里

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 2018-11-06
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多