mcpField
R
react-components

react-components

github.com/langchain-ai开发11985 次安装12 周前更新
代码仓库

关于 react-components

为开发者提供可维护 React 组件的编写模式,涵盖函数组件、Hooks 与组合方式。

主要功能

  1. 01使用 Hooks 编写函数组件
  2. 02提取可复用的自定义 Hook
  3. 03以组合避免属性层层传递

适用场景

  1. 01用 Hooks 组织 React 组件
  2. 02将异步逻辑提取为自定义 Hook
  3. 03组合组件以减少属性层层传递

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/langchain-ai/skills-benchmarks --skill react-components

安装后在 Claude Code 中输入/react-components确认已加载。

详细介绍

React 组件模式

使用现代模式构建易于维护的 React 组件。

使用 Hooks 的函数组件

始终优先使用函数组件,而非类组件:

import { useState, useEffect, useCallback } from 'react';

interface UserProps {
  userId: string;
  onUpdate?: (user: User) => void;
}

export function UserProfile({ userId, onUpdate }: UserProps) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchUser(userId).then(setUser).finally(() => setLoading(false));
  }, [userId]);

  const handleSave = useCallback(async (data: UserData) => {
    const updated = await updateUser(userId, data);
    setUser(updated);
    onUpdate?.(updated);
  }, [userId, onUpdate]);

  if (loading) return <Skeleton />;
  if (!user) return <NotFound />;

  return <UserForm user={user} onSave={handleSave} />;
}

自定义 Hooks

将可复用逻辑提取到自定义 Hooks 中:

function useAsync<T>(asyncFn: () => Promise<T>, deps: any[]) {
  const [state, setState] = useState<AsyncState<T>>({
    loading: true,
    error: null,
    data: null,
  });

  useEffect(() => {
    setState(s => ({ ...s, loading: true }));
    asyncFn()
      .then(data => setState({ loading: false, error: null, data }))
      .catch(error => setState({ loading: false, error, data: null }));
  }, deps);

  return state;
}

组件组合

使用组合,而非逐层传递属性:

<Card>
  <Card.Header>Title</Card.Header>
  <Card.Body>{content}</Card.Body>
  <Card.Footer>
    <Button>Action</Button>
  </Card.Footer>
</Card>

评论

支持 Markdown