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

纵饮孤独 提交于 2019-12-05 12:26:10

问题


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.

If i have something like

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

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


回答1:


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.




回答2:


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

file1 myClass.js:

export default class myClass {...}

file2 app.js:

import myClass from './myClass';

This is the basic version using a single default export. You can also export named exports that have to be explicitly listed on import. For more info see export and import.



来源:https://stackoverflow.com/questions/32923572/react-native-how-to-split-a-file-up-into-multiple-files-and-import-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!