繁体   English   中英

TypeScript 错误:(具有 MUI 样式的组件)不能用作 JSX 元素

[英]TypeScript error: (component with MUI style) cannot be used as a JSX element

我不明白我做错了什么。 我正在尝试将子组件添加到主页。 我推断它与最后应用的 MUI 样式有关。 我剥离了所有不相关的代码,但我仍然面临这个错误。 这不是实现 withStyles 的正确方法吗?

我正在尝试将表放在一个单独的组件中并在那里处理所有数据管理。 该组件将在主页上呈现。 我正在使用 React 16.13.1、material-ui 4.12.4、@types/react 16.9.56、typescript 4.0.2

数据表.tsx

 import React, { FC } from 'react'; import { createStyles, Theme, WithStyles } from "@material-ui/core/styles"; import Table from '@material-ui/core/Table' import Paper from "@material-ui/core/Paper"; import withStyles from "@material-ui/core/styles/withStyles"; interface TableProps { data: any; mode: string; parent: any; } const styles = (theme: Theme) => createStyles({ root: { width: "100%" // marginTop: theme.spacing(3), }, }) type CombinedProps = TableProps & WithStyles<typeof styles>; const DataTable: FC<CombinedProps> = (props: CombinedProps) => { return ( <> <div> <Paper style={{ overflow: "auto", height: "100%" }}> <Table> {/* TODO */} </Table> </Paper> </div> </> ); } export default withStyles(styles)(DataTable);

主页.tsx

 import React, { FC } from 'react'; import DataTable from './DataTable'; export const MainPage: FC = () => { let analysis = {'data': 0}; return ( <> {analysis ? <div> <DataTable data={analysis} mode={"comp_count"} parent={this}/> </div> : <div /> } </> ); };

我得到的错误:

'DataTable' cannot be used as a JSX component.
  Its element type 'ReactElement<any, any> | Component<Pick<TableProps & { classes: ClassNameMap<"root">; } & { children?: ReactNode; }, keyof TableProps | "children"> & StyledComponentProps<...>, any, any> | null' is not a valid JSX element.
    Type 'Component<Pick<TableProps & { classes: ClassNameMap<"root">; } & { children?: ReactNode; }, keyof TableProps | "children"> & StyledComponentProps<...>, any, any>' is not assignable to type 'Element | ElementClass | null'.
      Type 'Component<Pick<TableProps & { classes: ClassNameMap<"root">; } & { children?: ReactNode; }, keyof TableProps | "children"> & StyledComponentProps<...>, any, any>' is not assignable to type 'ElementClass'.
        The types returned by 'render()' are incompatible between these types.
          Type 'React.ReactNode' is not assignable to type 'import("/home/username/Git/projectname/frontend/node_modules/@types/react-router/node_modules/@types/react/index").ReactNode'.
            Type '{}' is not assignable to type 'ReactNode'.  TS2786

找到了解决方案:

withStyles并改用makeStyles

interface DataTableProps {
  data: any;
  mode: string;
  parent: any;
}

const useStyles = makeStyles({
  root: {
    width: "100%"
  },
})

const DataTable: FC<DataTableProps> = (props: DataTableProps) => {
  const classes = useStyles();
  return (
    <>
      <div className={classes.root}>
        {/* more code */}
      </div>
    </>);}

export default DataTable;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM