从其他目录中导出多个反应物体

时间:2017-12-07 04:38:53

标签: reactjs

我对React很新,所以请原谅我的无知。我基本上想知道从目录中导出多个ReactJS对象的“方法”,以获得更大的代码库和最佳实践。这实际上不在ReactJS tutorial

假设我有一个文件./main.js,我想导入一个lib(来自一个目录,因为我可能有其他的)。

假设我在dir ./library_dir/my_lib.js中有一个库,我想在./main.js中使用它。

./main.js中,我可能想要使用此lib并初始化一些ExampleComponent,如下所示:

var my_lib = require('./library_dir/my_lib.js');

ReactDOM.render(
(<BrowserRouter>
        <Switch>
                <Route exact path="/component_route" component={my_lib.ExampleComponent}>
        </Switch>
</BrowserRouter>)
, document.getElementById("root"));

所以在./library_dir/my_lib.js中,我希望能够导出MULTIPLE reactjs类。我该怎么做?

我想使用export default ....还是module.exports?哪一个和为什么?我已经读过,如果我在这个lib中import react,我就不能做module.exports

有人可以给我一个例子,在./library_dir/my_lib.js中,我可以导出多个看起来像这样的反应类吗?

import React from 'react';

my_lib = { 
        test_function: function() {
                alert("TEST FUNCTION CALLED");
        },  
        // How would I do this bellow?
        ExampleComonent: class ExampleComponent extends React.Component {
                constructor(props) {
                        super(props);
                        // doing all thing things...
                }
                render() {
                        return (
                        <h1>This is ExampleComponent.</h1>
                        );
                }
        }   
        // I need to be able to export multiple components, so here's another one.
        ExampleComonentTwo: class ExampleComponentTwo extends React.Component {
                constructor(props) {
                        super(props);
                        // doing all thing things...
                }
                render() {
                        return (
                        <h1>This is ExampleComponentTwo.</h1>
                        );
                }
        }
}

export default my_lib;

1 个答案:

答案 0 :(得分:0)

我们知道module是一个具有exports属性的纯JavaScript对象。 exports是一个普通的JavaScript变量,恰好设置为module.exportsexport default是来自ES6的语法。

许多人认为module.exports = ...等同于export default ...exports.foo ...等同于export const foo = ...。但这并不完全正确,或者至少不是巴贝尔如何做到这一点。

ES6 default导出实际上也是名为的导出,但default是“保留”名称,并且有特殊的语法支持。让我们看看Babel如何编译命名和默认导出:

// input
export const foo = 42;
export default 21;

// output
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
var foo = exports.foo = 42;
exports.default = 21; 

在这里,我们可以看到默认导出成为exports对象上的属性,就像foo一样。

我建议您使用一个index.js文件,您必须从lib中导出组件并在实际实现中使用它们。

我认为以下链接可以帮助您解决问题。

  1. Why es6 react component works only with “export default”?
  2. Multiple React components in a single module
  3. 希望这会对你有所帮助!!