繁体   English   中英

如何初始化和使用其他模块(WebPack和ES6)导出的ReactJS类?

[英]How do I initialize and use exported ReactJS classes from other modules (with WebPack and ES6)?

我正在使用WebPack和ES6,因此无法使用module.exports而必须使用export default 我有一个像这样的图书馆:

// helloworld.js
import React from 'react';

class HelloWorld extends React.Component {
        test() {
                alert("TEST FROM test()");
        }   
        render() {
                alert("TEST");
                return (
                        <p>Hello, world!</p>
                );  
        }   
}

// THIS WORKS WHEN I REQUIRE THIS MODULE
// var thing = new HelloWorld();
// thing.test();

export default HelloWorld;

当我var helloworld = require('helloworld.js');时,注释掉的部分起作用 ,但我无法弄清楚如何在需要的地方初始化和使用该对象。

这些尝试均无效。 如何初始化该对象并使用它?

// hello_world.test();
// hello_world.HelloWorld.test();
// var thing = new hello_world();
// var thing = new hello_world.HelloWorld();

我的主要原因是因为我需要使用ReactRouter这样的路由中的组件,而这些尝试均无效。

我尝试过这个(波纹管),这告诉我检查render方法...

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)

这个(波纹管)呈现空白页面!

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world.HelloWorld}/>
        </Switch>
</BrowserRouter>)

我没主意了。 无济于事。 无论是做这个 可以请别人借给我一些指示吗?

编辑:

解决方案只是在require的末尾添加defaultvar hello_world = require('./helloworld.js').default; )。 这可以在如下路径中使用它: <Route exact path="/helloworld" component={hello_world}/>

如果要在范围之外使用此功能,则可以执行以下操作:

var thing = new hello_world();
thing.test();

工作解决方案:

var hello_world = require('./hello_world.js').default; // Must add default.

// Using it outside a route, with a class method called test().
var thing = new hello_world();
thing.test();

// Using it in a router (ReactRouter with Switch).
ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/helloworld" component={hello_world}/>
        </Switch>
</BrowserRouter>)
, document.getElementById("root"));

您应该能够在常规jsx文件中使用该组件,如下所示:

var HelloWorld = require('path/to/HelloWorld.jsx');
...    
<div>
    <HelloWorld></HelloWorld>
</div>

或在react-router组件中,使用相同的require语句,如下所示:

var HelloWorld = require('path/to/HelloWorld.jsx');
....
<Route exact path="/helloworld" component={HelloWorld}/>

var helloworld = require('helloworld.js').default对我有用。 你能检查一下吗? 如果我在这里做错了,请指导我。

暂无
暂无

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

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