阿里云主机折上折
  • 微信号
Current Site:Index > Component naming conventions

Component naming conventions

Author:Chuan Chen 阅读数:13178人阅读 分类: 前端综合

Component development standards and naming conventions are an essential part of front-end engineering. Well-defined standards and conventions enhance code readability, maintainability, and team collaboration efficiency. From component design principles to specific naming rules, clear constraints and best practices need to be established.

Component Development Standards

Single Responsibility Principle

Each component should focus on a single specific functionality or UI part. Avoid creating multifunctional monolithic components. When a component exceeds 300 lines of code, consider splitting it.

// Bad Practice - Mixing presentation and logic
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetchUser(userId).then(setUser);
  }, [userId]);

  return (
    <div className="profile">
      <h2>{user?.name}</h2>
      <p>{user?.bio}</p>
      <button onClick={() => editUser(user)}>Edit</button>
    </div>
  );
}

// Good Practice - Separating container and presentation components
function UserProfileContainer({ userId }) {
  const [user, setUser] = useState(null);
  
  useEffect(() => {
    fetchUser(userId).then(setUser);
  }, [userId]);

  return <UserProfileView user={user} onEdit={editUser} />;
}

function UserProfileView({ user, onEdit }) {
  return (
    <div className="profile">
      <h2>{user?.name}</h2>
      <p>{user?.bio}</p>
      <button onClick={() => onEdit(user)}>Edit</button>
    </div>
  );
}

Clear Props Definition

Use TypeScript or PropTypes to explicitly define component interfaces, including:

  • Required/optional properties
  • Property types
  • Default values
  • Property descriptions
interface ButtonProps {
  /**
   * Button type
   * @default 'primary'
   */
  type?: 'primary' | 'secondary' | 'danger';
  /**
   * Button size
   */
  size?: 'small' | 'medium' | 'large';
  /**
   * Click event handler
   */
  onClick?: () => void;
  /**
   * Whether the button is disabled
   */
  disabled?: boolean;
  /**
   * Button text
   */
  children: React.ReactNode;
}

const Button: React.FC<ButtonProps> = ({
  type = 'primary',
  size = 'medium',
  onClick,
  disabled = false,
  children
}) => {
  // Component implementation
};

State Management Standards

  • Avoid duplicating the same state across multiple components
  • Lift state to the nearest common ancestor component
  • For complex state, consider using Context or state management libraries
  • Form components should implement the controlled component pattern
// Controlled component example
function SearchInput({ value, onChange }) {
  return (
    <input
      type="text"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder="Search..."
    />
  );
}

// Usage
function SearchPage() {
  const [searchTerm, setSearchTerm] = useState('');
  
  return (
    <div>
      <SearchInput value={searchTerm} onChange={setSearchTerm} />
      <SearchResults query={searchTerm} />
    </div>
  );
}

Styling Solutions

  • CSS Modules: Recommended for component-level style isolation
  • CSS-in-JS: Suitable for dynamic styling needs
  • Avoid global style pollution
  • Use design system spacing and color variables
// Button.module.scss
.button {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;

  &-primary {
    background-color: var(--color-primary);
    color: white;
  }

  &-disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

Documentation and Examples

Each component should include:

  1. Usage examples
  2. API documentation
  3. Interaction instructions
  4. Notes and considerations

Use tools like Storybook to maintain component documentation.

## Button

Commonly used action button.

### Basic Usage

```jsx
<Button type="primary" onClick={() => alert('Clicked')}>
  Confirm
</Button>

API

Prop Description Type Default
type Button type 'primary' | 'secondary' | 'danger' 'primary'
size Button size 'small' | 'medium' | 'large' 'medium'
disabled Whether disabled boolean false

## Component Naming Conventions

### File Naming  
- Use PascalCase for component files
- Match the default exported component name
- Add `.test` suffix for test files
- Use modular naming for style files

components/ Button/ Button.tsx Button.module.scss Button.test.tsx Button.stories.tsx


### Component Naming  
- Use PascalCase for component names
- Names should clearly describe the component's purpose
- Avoid generic names like "Item" or "Component"
- Use "with" prefix for higher-order components

```jsx
// Good naming
function UserAvatar() {}
function ShoppingCartItem() {}
function withAuth() {}

// Bad naming
function Avatar() {} // Too generic
function Item() {} // Meaningless
function auth() {} // Doesn't follow convention

Props Naming

  • Use camelCase for props
  • Boolean props should start with is/has/can
  • Event handlers should start with on
  • Avoid DOM attribute names like class/for
<Modal
  isOpen={true}
  onClose={handleClose}
  title="Confirm"
  showFooter={false}
/>

CSS Class Naming

  • Use BEM or similar methodology
  • Avoid element tag selectors
  • Prefix with the component name
  • Use is- prefix for state classes
// BEM example
.user-card {
  &__header {
    font-size: 16px;
  }
  
  &__avatar {
    width: 40px;
    
    &--large {
      width: 60px;
    }
  }
  
  &.is-active {
    border-color: blue;
  }
}

Directory Structure Standards

Organize components by feature or business domain to avoid a monolithic "components" directory.

src/
  components/
    ui/               # Generic UI components
      Button/
      Input/
      Modal/
    features/         # Business feature components
      checkout/
        CartItem.tsx
        PaymentForm.tsx
    layouts/          # Layout components
      MainLayout/
      AuthLayout/

Test File Naming

  • Place test files in the same directory as the component
  • Naming pattern: ComponentName.test.tsx
  • Place utility tests in __tests__ directories
utils/
  dateFormatter.ts
  __tests__/
    dateFormatter.test.ts

Type Definition Naming

  • Component props type: ComponentNameProps
  • Complex types use Type or Interface suffix
  • Enum types use plural form
interface ModalProps {
  title: string;
  onClose: () => void;
}

type ButtonVariants = 'primary' | 'secondary' | 'text';

enum UserRoles {
  Admin,
  Editor,
  Viewer
}

Version Control and Changelog

Component Version Management

  • Follow Semantic Versioning (SemVer)
  • Major changes require major version upgrades
  • Maintain CHANGELOG.md to record changes
## [1.2.0] - 2023-05-15

### Added
- Added loading state prop to Button component

### Changed
- Optimized Modal component animation effects

### Fixed
- Fixed Input component styling issues in Safari

Handling Breaking Changes

  • Deprecated APIs should issue warnings
  • Provide migration guides
  • Maintain backward compatibility for at least one major version
// Handling deprecated props
function Button({ size, scale, ...props }) {
  if (scale) {
    console.warn('"scale" prop is deprecated, please use "size" instead');
    size = scale;
  }
  
  return <button className={`btn-${size}`} {...props} />;
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:组件设计原则

下一篇:目录结构规范

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.