反应导入材料UI组件不起作用

时间:2019-12-11 21:31:22

标签: javascript reactjs import material-ui

我是React的新手。我有一个本地开发服务器(节点http-server),并且已经安装了material-ui软件包。

根据material-ui文档,要添加组件,我只需像导入其他模块一样将其导入:

import Button from '@material-ui/core/Button';

但是,当我尝试此操作时,我的网络服务器返回了404,而Firefox控制台输出了以下内容:Loading module from “http://localhost:8080/node_modules/@material-ui/core/Button/” was blocked because of a disallowed MIME type (“text/html”)

可以访问该目录,因为我可以引用./node_modules/@material-ui/core/Button/Button.js文件,并且该目录由http-server返回。但是,如果我导入该文件,则会得到

SyntaxError: import not found: default.

我尝试从该目录导入index.js,但遇到相同的错误。

如何正确导入Button组件(如material-ui示例所示)?

这是我的代码(由localhost:8080上的http服务器提供) (我正在使用npx babel在投放之前将JSX编译为js)

test.html:

<!doctype html>
<html>
<head>

    <meta charset="UTF-8">

    <title>Test React</title>

    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
</head>
<body>
    <div id="app"></div>


    <!-- React scripts -->


    <script type="module" src="./test.js"></script>
</body>
</html>

test.js:

import { Mod1 } from './module1.js';
export class TestComponent extends React.Component
{
    render()
    {
        return <h1>Hello world!</h1>;
    }
}

export const TestC2 = () => 
{
    return <h2>This is a h2</h2>;
}



ReactDOM.render(<div><TestComponent /><TestC2 /><Mod1 /></div>, document.getElementById('app'));

module1.js

// module1
import Button from './node_modules/@material-ui/core/Button';
export class Mod1 extends React.Component
{
    constructor(props)
    {
        super(props);

        this.state = {};


    }

    componentWillMount(props)
    {
        console.log("willMount", props);
    }

    componentDidMount(pp, ps)
    {
        console.log("didMount", pp, ps);
    }

    render()
    {
        console.log('render', this.props, this.state);
        return <Button />;
    }
}

0 个答案:

没有答案
相关问题