搜索
首页web前端js教程组织前端项目的组件文件夹

Organizing the Frontend project

文件夹结构前端项目的组件非常重要。因为它使项目的开发和维护变得更加容易。特别是在处理大型或复杂的组件时,组织文件夹有助于使代码井井有条,并且更易于查找和理解

这是文件夹结构。各种格式的组件常用于使用开发的项目Next.jsTypeScript:

1. 原子设计结构

原子设计是一种根据组件的复杂性和功能来划分组件的设计概念。它分为5个级别:原子、分子、有机体、模板和页面。

src/
└── components/
    ├── atoms/             # Small, reusable elements (e.g., buttons, inputs)
    │   ├── Button.tsx
    │   ├── Input.tsx
    │   ├── Icon.tsx
    │   └── ...            # Additional atoms
    │
    ├── molecules/         # Combinations of atoms (e.g., form groups)
    │   ├── FormInput.tsx
    │   ├── NavLink.tsx
    │   └── ...            # Additional molecules
    │
    ├── organisms/         # Complex UI components (e.g., headers, cards)
    │   ├── Header.tsx
    │   ├── Card.tsx
    │   ├── Footer.tsx
    │   └── ...            # Additional organisms
    │
    ├── templates/         # Page templates (layouts with placeholders)
    │   ├── MainLayout.tsx
    │   ├── DashboardLayout.tsx
    │   └── ...            # Additional templates
    │
    └── pages/             # Page-specific components (used directly in pages)
        ├── HomePage.tsx
        ├── AboutPage.tsx
        └── ...            # Additional page components

例子:

原子:Button.tsx

import React from 'react';

interface ButtonProps {
  label: string;
  onClick: () => void;
  type?: 'button' | 'submit' | 'reset';
  disabled?: boolean;
}

const Button: React.FC<buttonprops> = ({ label, onClick, type = 'button', disabled = false }) => (
  <button type="{type}" onclick="{onClick}" disabled classname="btn">
    {label}
  </button>
);

export default Button;
</buttonprops>

分子:FormInput.tsx

import React from 'react';
import Input from '../atoms/Input';
import Label from '../atoms/Label';

interface FormInputProps {
  label: string;
  value: string;
  onChange: (value: string) => void;
}

const FormInput: React.FC<forminputprops> = ({ label, value, onChange }) => (
  <div classname="form-input">
    <label text="{label}"></label>
    <input value="{value}" onchange="{onChange}">
  </div>
);

export default FormInput;
</forminputprops>

生物体:Header.tsx

import React from 'react';
import NavLink from '../molecules/NavLink';
import Logo from '../atoms/Logo';

const Header: React.FC = () => (
  <header classname="header">
    <logo></logo>
    <nav>
      <navlink href="/" label="Home"></navlink>
      <navlink href="/about" label="About"></navlink>
      <navlink href="/contact" label="Contact"></navlink>
    </nav>
  </header>
);

export default Header;

2. 基于特征的结构

按功能或模块分隔组件的结构在功能丰富的项目中很流行。帮助高效管理和扩展功能

src/
└── components/
    ├── authentication/    # Components related to authentication
    │   ├── Login.tsx
    │   ├── Signup.tsx
    │   └── PasswordReset.tsx
    │
    ├── dashboard/         # Components specific to the dashboard
    │   ├── DashboardHeader.tsx
    │   ├── DashboardSidebar.tsx
    │   └── StatsCard.tsx
    │
    ├── userProfile/       # Components for user profile
    │   ├── ProfileHeader.tsx
    │   ├── EditProfileForm.tsx
    │   └── Avatar.tsx
    │
    ├── shared/            # Shared or common components across features
    │   ├── Button.tsx
    │   ├── Modal.tsx
    │   └── ...            # Additional shared components
    │
    └── layout/            # Layout components
        ├── Header.tsx
        ├── Footer.tsx
        └── Sidebar.tsx

例子:

身份验证:Login.tsx

import React, { useState } from 'react';
import Button from '../shared/Button';
import FormInput from '../shared/FormInput';

const Login: React.FC = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = () => {
    // Logic for login
  };

  return (
    <div classname="login">
      <h2 id="Login">Login</h2>
      <forminput label="Email" value="{email}" onchange="{setEmail}"></forminput>
      <forminput label="Password" value="{password}" onchange="{setPassword}"></forminput>
      <button label="Login" onclick="{handleLogin}"></button>
    </div>
  );
};

export default Login;

仪表板:StatsCard.tsx

import React from 'react';

interface StatsCardProps {
  title: string;
  value: number;
  icon: React.ReactNode;
}

const StatsCard: React.FC<statscardprops> = ({ title, value, icon }) => (
  <div classname="stats-card">
    <div classname="stats-card-icon">{icon}</div>
    <div classname="stats-card-info">
      <h3 id="title">{title}</h3>
      <p>{value}</p>
    </div>
  </div>
);

export default StatsCard;
</statscardprops>

3. 领域驱动结构

此结构侧重于根据项目的域或有界上下文来组织组件。这使得这种结构适合需要明确域分离的复杂系统

src/
└── components/
    ├── domain/
    │   ├── product/       # Components related to product domain
    │   │   ├── ProductCard.tsx
    │   │   ├── ProductList.tsx
    │   │   └── ProductDetail.tsx
    │   │
    │   ├── cart/          # Components for cart domain
    │   │   ├── CartItem.tsx
    │   │   ├── CartSummary.tsx
    │   │   └── CartIcon.tsx
    │   │
    │   ├── user/          # Components for user domain
    │   │   ├── UserAvatar.tsx
    │   │   ├── UserProfile.tsx
    │   │   └── UserSettings.tsx
    │   │
    │   └── ...            # Additional domain-specific components
    │
    ├── ui/                # UI elements (atoms, molecules, etc.)
    │   ├── atoms/         
    │   ├── molecules/     
    │   └── organisms/     
    │
    └── layout/            # Layout components
        ├── Header.tsx
        ├── Footer.tsx
        └── Sidebar.tsx

例子:

产品:ProductCard.tsx

import React from 'react';

interface ProductCardProps {
  name: string;
  price: number;
  imageUrl: string;
  onAddToCart: () => void;
}

const ProductCard: React.FC<productcardprops> = ({ name, price, imageUrl, onAddToCart }) => (
  <div classname="product-card">
    <img src="%7BimageUrl%7D" alt="{name}" classname="product-card-image">
    <div classname="product-card-info">
      <h3 id="name">{name}</h3>
      <p>${price.toFixed(2)}</p>
      <button onclick="{onAddToCart}">Add to Cart</button>
    </div>
  </div>
);

export default ProductCard;
</productcardprops>

购物车:CartSummary.tsx

import React from 'react';

interface CartSummaryProps {
  totalItems: number;
  totalPrice: number;
}

const CartSummary: React.FC<cartsummary props> = ({ totalItems, totalPrice }) => (
  <div classname="cart-summary">
    <h3 id="Cart-Summary">Cart Summary</h3>
    <p>Total Items: {totalItems}</p>
    <p>Total Price: ${totalPrice.toFixed(2)}</p>
    <button>Checkout</button>
  </div>
);

export default CartSummary;
</cartsummary>

4. 使用 Storybook 进行组件驱动开发 (CDD)

该结构旨在支持跨平台开发。 组件驱动开发 (CDD) 使用 Storybook,它允许您以独立于主应用程序的格式开发和测试组件

src/
└── components/
    ├── Button/
    │   ├── Button.tsx      # Component implementation
    │   ├── Button.stories.tsx # Storybook stories
    │   ├── Button.test.tsx # Unit tests
    │   └── Button.module.css # Component-specific styles
    │
    ├── Input/
    │   ├── Input.tsx
    │   ├── Input.stories.tsx
    │   ├── Input.test.tsx
    │   └── Input.module.css
    │
    ├── Modal/
    │   ├── Modal.tsx
    │   ├── Modal.stories.tsx
    │   ├── Modal.test.tsx
    │   └── Modal.module.css
    │
    └── ...                # Additional component folders

例子:

按钮:Button.tsx

import React from 'react';
import styles from './Button.module.css';

interface ButtonProps {
  label: string;
  onClick: () => void;
  variant?: 'primary' | 'secondary';
}

const Button: React.FC<buttonprops> = ({ label, onClick, variant = 'primary' }) => (
  <button classname="{`${styles.btn}" onclick="{onClick}">
    {label}
  </button>
);

export default Button;
</buttonprops>

按钮:Button.stories.tsx(故事书)

import React from 'react';
import { Meta, Story } from '@storybook/react';
import Button, { ButtonProps } from './Button';

export default {
  title: 'Components/Button',
  component: Button,
} as Meta;

const Template: Story<buttonprops> = (args) => <button></button>;

export const Primary = Template.bind({});
Primary.args = {
  label: 'Primary Button',
  onClick: () => console.log('Primary Button Clicked'),
  variant: 'primary',
};

export const Secondary = Template.bind({});
Secondary.args = {
  label: 'Secondary Button',
  onClick: () => console.log('Secondary Button Clicked'),
  variant: 'secondary',
};
</buttonprops>

5. 共享组件库

在多个团队一起工作的项目中创建使用通用组件的结构很重要。这种结构强调分离可以在整个项目中重用的组件

src/
└── components/
    ├── shared/            # Shared components across the application
    │   ├── Button/
    │   │   ├── Button.tsx
    │   │   └── Button.module.css
    │   │
    │   ├── Modal/
    │   │   ├── Modal.tsx
    │   │   └── Modal.module.css
    │   │
    │   └── ...            # Additional shared components
    │
    ├── featureSpecific/   # Feature-specific components
    │   ├── UserProfile/
    │   │   ├── ProfileHeader.tsx
    │   │   ├── ProfileDetails.tsx
    │   │   └── Avatar.tsx
    │   │
    │   ├── ProductList/
    │   │   ├── ProductCard.tsx
    │   │   └── ProductFilter.tsx
    │   │
    │   └── ...            # Additional feature-specific components
    │
    └── layout/            # Layout components
        ├── Header.tsx
        ├── Footer.tsx
        └── Sidebar.tsx

ตัวอย่าง:

Shared: Modal.tsx

import React from 'react';
import styles from './Modal.module.css';

interface ModalProps {
  title: string;
  isOpen: boolean;
  onClose: () => void;
}

const Modal: React.FC<modalprops> = ({ title, isOpen, onClose, children }) => {
  if (!isOpen) return null;

  return (
    <div classname="{styles.modalOverlay}">
      <div classname="{styles.modal}">
        <h2 id="title">{title}</h2>
        <button classname="{styles.closeButton}" onclick="{onClose}">
          ×
        </button>
        <div classname="{styles.modalContent}">{children}</div>
      </div>
    </div>
  );
};

export default Modal;
</modalprops>

Feature-Specific: ProfileHeader.tsx

import React from 'react';

interface ProfileHeaderProps {
  name: string;
  bio: string;
  avatarUrl: string;
}

const ProfileHeader: React.FC<profileheaderprops> = ({ name, bio, avatarUrl }) => (
  <div classname="profile-header">
    <img src="%7BavatarUrl%7D" alt="{name}" classname="profile-avatar">
    <h1 id="name">{name}</h1>
    <p>{bio}</p>
  </div>
);

export default ProfileHeader;
</profileheaderprops>

Factors to Consider When Structuring Components

  1. Reusability: ควรแยก component ที่สามารถใช้ซ้ำได้ออกจาก component ที่เฉพาะเจาะจงกับฟีเจอร์
  2. Maintainability: การจัดโครงสร้างที่ดีช่วยให้การดูแลรักษาและการอัพเดตโปรเจคเป็นไปอย่างราบรื่น
  3. Scalability: โครงสร้างที่ดีจะช่วยให้การขยายฟีเจอร์และการเพิ่ม component ใหม่ ๆ เป็นเรื่องง่าย
  4. Performance: ใช้เทคนิคที่เหมาะสมในการโหลดและใช้ component เพื่อให้แน่ใจว่าแอปพลิเคชันของคุณมีประสิทธิภาพ

Best Practices for Component Structure

  • Single Responsibility Principle: แต่ละ component ควรทำหน้าที่เดียวและทำได้ดี
  • Component Naming: ตั้งชื่อ component ให้สื่อความหมายและชัดเจน
  • Component Composition: ใช้ composition แทน inheritance เมื่อสร้าง component ใหม่
  • Use Prop Types or TypeScript: กำหนด prop types หรือใช้ TypeScript interfaces เพื่อเพิ่มความปลอดภัยในการใช้งาน
  • Write Tests: เขียน unit tests สำหรับ component ทุกตัวเพื่อตรวจสอบการทำงาน

ด้วยข้อมูลและแนวทางเหล่านี้ หวังว่าคุณจะสามารถจัดโครงสร้างในโฟลเดอร์ components ของโปรเจคได้อย่างมีประสิทธิภาพและเหมาะสมกับความต้องการของโปรเจคของคุณ!

以上是组织前端项目的组件文件夹的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JavaScript的演变:当前的趋势和未来前景JavaScript的演变:当前的趋势和未来前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趋势包括TypeScript的崛起、现代框架和库的流行以及WebAssembly的应用。未来前景涵盖更强大的类型系统、服务器端JavaScript的发展、人工智能和机器学习的扩展以及物联网和边缘计算的潜力。

神秘的JavaScript:它的作用以及为什么重要神秘的JavaScript:它的作用以及为什么重要Apr 09, 2025 am 12:07 AM

JavaScript是现代Web开发的基石,它的主要功能包括事件驱动编程、动态内容生成和异步编程。1)事件驱动编程允许网页根据用户操作动态变化。2)动态内容生成使得页面内容可以根据条件调整。3)异步编程确保用户界面不被阻塞。JavaScript广泛应用于网页交互、单页面应用和服务器端开发,极大地提升了用户体验和跨平台开发的灵活性。

Python还是JavaScript更好?Python还是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。 1.Python以简洁语法和丰富库生态着称,适用于数据分析和Web开发。 2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

如何安装JavaScript?如何安装JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript不需要安装,因为它已内置于现代浏览器中。你只需文本编辑器和浏览器即可开始使用。1)在浏览器环境中,通过标签嵌入HTML文件中运行。2)在Node.js环境中,下载并安装Node.js后,通过命令行运行JavaScript文件。

在Quartz中如何在任务开始前发送通知?在Quartz中如何在任务开始前发送通知?Apr 04, 2025 pm 09:24 PM

如何在Quartz中提前发送任务通知在使用Quartz定时器进行任务调度时,任务的执行时间是由cron表达式设定的。现�...

在JavaScript中,如何在构造函数中获取原型链上函数的参数?在JavaScript中,如何在构造函数中获取原型链上函数的参数?Apr 04, 2025 pm 09:21 PM

在JavaScript中如何获取原型链上函数的参数在JavaScript编程中,理解和操作原型链上的函数参数是常见且重要的任�...

微信小程序webview中Vue.js动态style位移失效是什么原因?微信小程序webview中Vue.js动态style位移失效是什么原因?Apr 04, 2025 pm 09:18 PM

在微信小程序web-view中使用Vue.js动态style位移失效的原因分析在使用Vue.js...

在Tampermonkey中如何实现对多个链接的并发GET请求并依次判断返回结果?在Tampermonkey中如何实现对多个链接的并发GET请求并依次判断返回结果?Apr 04, 2025 pm 09:15 PM

在Tampermonkey中如何对多个链接进行并发GET请求并依次判断返回结果?在Tampermonkey脚本中,我们经常需要对多个链...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。