javascript React Native:如何将文件拆分为多个文件并导入它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32923572/
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-10-28 15:55:18  来源:igfitidea点击:

React Native: How to split a file up into multiple files and import them?

javascriptreact-nativelibrariescode-reusecode-structure

提问by Patrick Klitzke

I am writing my first app in react native and my js file is getting pretty big. What is the proper way to split the file up.

我正在用 React Native 编写我的第一个应用程序,我的 js 文件变得越来越大。拆分文件的正确方法是什么。

If i have something like

如果我有类似的东西

var MyClass = React.createClass({
  ...
})

Can I save it at myclass.jsand include in by some command in another js file?

我可以将它保存myclass.js并包含在另一个 js 文件中的某个命令中吗?

采纳答案by webwelten

In general you can do the following:

一般来说,您可以执行以下操作:

var MyClass = React.createClass({
    ...
)}

module.exports = MyClass;

This way you tell what should be publicly available.

通过这种方式,您可以判断哪些内容应该公开可用。

And then, in your former big file you can load the contents like this:

然后,在您以前的大文件中,您可以像这样加载内容:

var MyClass = require('./myclass.js');

Require returns the object that references the value of module.exports.

Require 返回引用 module.exports 值的对象。

回答by Oswin Noetzelmann

Here is the updated solution with using the importstatement (in latest React-Native and generally Javascript adhering to ECMAScript6 and later):

这是使用该import语句的更新解决方案(在最新的 React-Native 中,并且通常遵循 ECMAScript6 及更高版本的 Javascript):

file1 myClass.js:

文件 1 myClass.js:

export default class myClass {...}

file2 app.js:

file2 app.js:

import myClass from './myClass';

This is the basic version using a single defaultexport. You can also export namedexports that have to be explicitly listed on import. For more info see exportand import.

这是使用单个default导出的基本版本。您还可以导出named必须在导入时明确列出的导出。有关更多信息,请参阅exportimport