gpt4 book ai didi

javascript - index.js 文件如何在 React 组件目录中工作?

转载 作者:IT王子 更新时间:2023-10-29 03:14:37 29 4
gpt4 key购买 nike

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

├── 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 在这种情况下是如何工作的。如引用:

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

本文没有做的是深入了解这些文件的内部。对于 Editable 组件,Editable.jsxindex.js 理想情况下应该是什么样子?

最佳答案

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

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

import Editable from './Editable.jsx';

export default Editable;

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

import Editable from '../Editable';

因为它默认尝试访问 index.js 文件,因此不需要您提供更多信息。它会自动导入导入实际组件本身的 index.js 文件。如果您没有 index.js 文件,您将不得不这样做:

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

这有点尴尬。我不喜欢有一个索引文件,它所做的只是导入一个组件并将其导出。我通常做的是将所有组件代码放在 index.js 文件中,根本不需要 Editable.jsx。这取决于您,所以请随意采用您更喜欢的方法。

关于javascript - index.js 文件如何在 React 组件目录中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44092341/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com