index.js文件如何在React组件目录中工作? [英] How do index.js files work in React component directories?

查看:406
本文介绍了index.js文件如何在React组件目录中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始一个新的React项目并决定使用 pattern,它基本上根据各自的组件对文件进行分组:

I just started a new React project and decided to use this pattern, which basically groups files according to their respective component:

├── actions
│   ├── LaneActions.js
│   └── NoteActions.js
├── components
│   ├── App
│   │   ├── App.jsx
│   │   ├── app.css
│   │   ├── app_test.jsx
│   │   └── index.js
│   ├── Editable
│   │   ├── Editable.jsx
│   │   ├── editable.css
│   │   ├── editable_test.jsx
│   │   └── index.js
...
│   └── index.js
├── constants
│   └── itemTypes.js
├── index.jsx
├── libs
│   ├── alt.js
│   ├── persist.js
│   └── storage.js
├── main.css
└── stores
    ├── LaneStore.js
    └── NoteStore.js

令我困惑的是index.js在这种情况下是如何工作的。引用:

What's confusing me is how index.js works in this case. As quoted:


index.js文件用于为
组件提供简单的入口点。即使它们增加了噪音,它们也会简化进口。

The index.js files are there to provide easy entry points for components. Even though they add noise, they simplify imports.

文章没有做的是深入了解里面的内容这些文件。在可编辑组件的情况下, Editable.jsx index.js 理想情况下会是什么样?

What the article doesn't do is go in depth of what's inside these files. In the case of the Editable component, what would Editable.jsx and index.js ideally look like?

推荐答案

这个确切的结构表明,例如,可编辑组件会有关于该组件的所有内容 Editable.jsx 。我的意思是你的组件代码保留在该文件中。

Well this exact structures suggests that, for example, the Editable component would have everything about that component inside Editable.jsx. and I mean that your component code stays inside that file.

现在索引是什么?在内部索引中,您只需执行以下操作:

Now what's index for ? Inside index you would simply do something like this:

import Editable from './Editable.jsx';

export default Editable;

这就是字面意思。这很有用,因为在其他组件或容器中你可以这样做:

and that's literally it. This is helpful because inside other components or containers you can do this:

import Editable from '../Editable';

因为它试图访问 index.js 默认情况下文件,因此不再需要您的任何信息。它会自动导入 index.js 文件,该文件导入实际组件本身。如果您没有 index.js 文件,则必须执行此操作:

because it tries to access the index.js file by default thus not requiring any more info from you. It would import automatically the index.js file which imports the actual component itself. If you did not have an index.js file you would have had to do this:

import Editable from '../Editable/Editable';

老实说有点尴尬。现在我个人不喜欢有一个索引文件,它只是导入一个组件并导出它。我通常做的是将所有组件代码放在 index.js 文件中,而不需要 Editable.jsx 一点都没。现在这取决于你,所以随意采取你更喜欢的方法。

which is honestly kind of awkward. Now I personally don't like to have an index file that all it does is import a component and export it. What I usually do is just have all my component code inside the index.js file without the need of the Editable.jsx at all. Now that's up to you so feel free to take the approach that you like better.

这篇关于index.js文件如何在React组件目录中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆