Javascript React 组件和模块导出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35860695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:17:32  来源:igfitidea点击:

React components and module exports

javascriptreactjsmodule

提问by akantoword

I don't understand how module.exports can only export one component that has a dependency on a subcomponent but still be rendered in the DOM although that sub component was never exported.

我不明白 module.exports 如何只能导出一个依赖于子组件但仍然在 DOM 中呈现的组件,尽管该子组件从未被导出。

//component.js

//组件.js

var SubComponent = React.createClass({
...
    });

var Component = React.createClass({
    ...
    render: function () { 
    return(
        <div><SubComponent /> stuff</div>`)
        }});

module.exports = Component

//main.js

//main.js

    var Component = require('./component.js');

    var MainContainer = React.createClass({
    render: function () {return (
    <Component />)
    }})

回答by Grzegorz Motyl

You are using only one component directly (Component) in your main.jsfile. SubComponentis not used outside component.js, therefore it doesn't have to be exported. If you want to use SubComponentin your main.jsfile you could use it like this:

Componentmain.js文件中仅直接使用了一个组件 ( ) 。SubComponent不在外部使用component.js,因此不必导出。如果你想SubComponent在你的main.js文件中使用,你可以像这样使用它:

//component.js

//组件.js

(...)
module.exports = {
    Component: Component,
    SubComponent: SubComponent
}

//main.js

//main.js

 var Component = require('./component.js').Component;
 var SubComponent = require('./component.js').SubComponent; (...)

Then you can use SubComponentdirectly in main.js

然后就可以SubComponent直接使用main.js