TypeScript 错误:(具有 MUI 样式的组件)不能用作 JSX 元素
2022-04-13
2652
我不明白我做错了什么。我正在尝试将子组件添加到主页。我推断它与最后应用的 MUI 样式有关。我删除了所有不相关的代码,但仍然面临此错误。这不是实现 withStyles 的正确方法吗?
我正在尝试将表放在单独的组件中并在那里处理所有数据管理。然后该组件将在主页上呈现。我使用的是 React 16.13.1、material-ui 4.12.4、@types/react 16.9.56、typescript 4.0.2
DataTable.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);
MainPage.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
1个回答
找到了解决方案:
放弃
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;
jogerj
2022-04-13