use*_*SI. 3 javascript reactjs
我最近开始了一个 react 项目,我发现一些带有 npm 的 util 命令可以自动生成一些项目。没问题,但项目结构对我来说有点混乱,所以我在谷歌上搜索了一些解释,一切都很好,我在https://www.pluralsight.com/guides/上发现了一些有趣的东西file-structure-react-applications-created-create-react-app :
虽然组件可以驻留在 src/components/my-component-name 中,但建议在该目录中有一个 index.js。因此,无论何时有人使用 src/components/my-component-name 导入组件,而不是导入目录,这实际上会导入 index.js 文件。
这个 index.js 文件,我应该如何创建它来返回组件?
例如我想为不同的路线创建一些页面:
import React, {Component} from 'react'
class MyPage extends Component{
render() {
return (
<div>
My Page
</div>
);
}
}
export default MyPage;
Run Code Online (Sandbox Code Playgroud)
现在,index.js 应该是这样的?
import React from "react";
import MyPage from "src/pages/MyPage";
const mypage = () => {
return <MyPage/>
};
export default mypage;
Run Code Online (Sandbox Code Playgroud)
和项目结构:
src
|___pages
|____MyPage.jsx
|____index.js
Run Code Online (Sandbox Code Playgroud)
路由器组件应该没有问题,因为没有index.js我要做的就是导入MyPage并执行以下操作:
<Router>
<div>
<Route path="/" component={MyPage} />
</div>
</Router>
Run Code Online (Sandbox Code Playgroud)
这是创建 index.js 文件的正确方法吗?
这绝对是您可以用来构建组件的策略。如果你想的话取决于你。index.jswebpack 的处理方式有所不同,因此您可以直接import MyPage from './components/MyPage'离开index.js。使用这种做法的常见方法是从 index.js 导入然后再次导出组件:
我的页面.js
const MyPage = () => <div>Hello world</div>;
export default MyPage;
Run Code Online (Sandbox Code Playgroud)
索引.js
import MyPage from './MyPage.js';
export default MyPage;
Run Code Online (Sandbox Code Playgroud)
小智 5
当您需要从给定文件夹导出大量组件,并且您希望在将它们导入的文件中进行解构时,使用 index.js 文件是很好的。您根本不必遵循这一点,但这样做仍然是最佳实践;从 Redux 中的 reducer 或具有大量较小组件(如 a<Button>或 )的实用程序文件夹导出大量文件<Input>时会更容易,如果所有内容合并为单个索引文件,其他用户也更容易阅读而不是几个不同的文件。
index.js
export {default as Input} from './Input';
export {default as Button} from './Button';
export {default as TextField} from './TextField';
Run Code Online (Sandbox Code Playgroud)
form.js
import {Input, Button, TextField} from './UtilityFile
Run Code Online (Sandbox Code Playgroud)
index.js 有一些特殊的属性,如果你从文件中导入,如果没有指定其他内容,javascript 将查找 index.js。无论哪种方式都有效,但对于使用 index.js 的更大规模应用程序是首选。
您引用的来源是关于create-react-app,但作者将自己的观点放在首位,并将其呈现为既定事实。
如果您真的查看create-react-app文档(这总是一个好主意:从源代码开始,如果官方文档没有涵盖您需要了解的内容,则转到教程),例如https://create-react-app .dev/docs/importing-a-component#buttonjs,您会看到它们准确地显示了您的文章所说的不要做的事情:它正在<Button>从名为button.js.
By all means, use an index.js if you want implicit imports (there are situations in which it is an excellent idea to do so), but create-react-app doesn't care, it does not "recommend to have an index.js inside that directory", and this article is simply being misleading. There are reasons for adding an index.js, and they are wholly unrelated to create-react-app, React in general, or even the practice of writing JS in class form.
| 归档时间: |
|
| 查看次数: |
3757 次 |
| 最近记录: |