[英]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的末尾添加default
( var 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.