在我的应用程序中大量使用资料-ui,有办法避免像这样在每个应用组件中进行导入吗?
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import Grid from "@material-ui/core/Grid";
import Container from "@material-ui/core/Container";
....或者这个:
import {Typography, Box, Grid, Container} from "@material-ui/core";有这样的事吗?这样我就不需要导入每个组件了?
import * from "@material-ui/core"提前谢谢!:D
发布于 2020-04-23 17:25:47
是的,在JavaScript中有一个import。你可以这样做:
import * as Mui from '@material-ui/core';这会将@material-ui/core的所有命名导出都放到Mui“命名空间”中。然后,您可以轻松地访问任何组件,即:
<Mui.Typography>Test</Mui.Typography>您可以阅读更多关于这里的内容。
发布于 2022-01-25 16:09:27
从导入语句的角度来看,第一个选项不太清晰,特别是当您希望导入和使用许多Mui组件时,但是当您使用path导入以避免使用未使用的模块时,将自动获得优化的包大小。
另一方面,第二个选项(import * from "@material-ui/core")从开发角度来看是最方便的,它还使您拥有一个干净的导入语句,但是将使您的应用程序包比它们单独导入每个组件更大,这取决于您正在使用的组件的哪个部分。此外,还需要从不同的材料来源导入大型应用程序-ui:
import {} from '@material-ui/core';
import {} from '@material-ui/icons';
import {} from '@mui/material';一个更好的优化方法是在项目中创建一个文件,在该文件中导入单独使用的每个组件,然后将它们全部导出到一个名称空间中:
// src/mui/index.js
export { default as MenuItem } from '@material-ui/core/MenuItem';
export { default as TextField } from '@material-ui/core/TextField';
export { default as Select } from '@material-ui/core/Select';
export { default as ClearIcon} from '@material-ui/icons/Clear';
export { default as FormControl } from '@material-ui/core/FormControl';
export { default as Button } from '@mui/material/Button';
...然后,您可以将该文件大量导入到需要它的每个组件中:
// ../../MyComponent.js
import {
MenuItem,
TextField,
Select,
ClearIcon,
FormControl
} from 'mui';现在,您有了一个干净的导入语句和优化的包大小。
使用绝对路径:我从不使用相对路径来寻址组件(e.i ./mui)。如果您不知道如何在React中使用绝对路径,您可以查看这里。
发布于 2020-04-23 17:19:52
嗨,你可以这样做:
从“@material ui/core/Button”导出{default as Button}; 从“@material ui/core/Card”导出{default as Card}; 从“@material ui/core/纸质”导出{默认值为纸张};
*作为“./ collections”中的集合导入;
组件文件将为:
import React, {Component} from "react";
import * as collections from './collections';
class Box extends Component {
render() {
return (
<div>
<collections.Button>
Test
</collections.Button>
<collections.Card>test</collections.Card>
<collections.Paper>test</collections.Paper>
</div>
);
}
}
export default Box;https://stackoverflow.com/questions/61390510
复制相似问题