当前位置:首页 > React

react如何开发组件

2026-01-13 08:44:32React

React 组件开发基础

React 组件分为函数组件类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。

函数组件示例:

function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

类组件示例:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

组件 Props 的使用

Props 是组件的只读属性,用于父子组件通信:

function UserCard(props) {
  return (
    <div>
      <h2>{props.user.name}</h2>
      <p>{props.user.email}</p>
    </div>
  );
}

// 使用组件
<UserCard user={{ name: "Alice", email: "alice@example.com" }} />

组件 State 管理

使用 useState Hook 管理组件内部状态:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

生命周期与副作用处理

使用 useEffect 处理副作用和生命周期:

import { useEffect } from 'react';

function DataFetcher({ userId }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(`/api/user/${userId}`)
      .then(res => res.json())
      .then(setData);
  }, [userId]); // 依赖数组控制执行时机
}

组件样式方案

React 支持多种样式方案:

  1. 内联样式

    <div style={{ color: 'red', fontSize: 16 }}>Text</div>
  2. CSS Modules

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

function Button() { return Submit; }


3. Styled-components:
```jsx
import styled from 'styled-components';

const StyledButton = styled.button`
  background: palevioletred;
  color: white;
`;

function Button() {
  return <StyledButton>Click</StyledButton>;
}

组件组合模式

通过组合实现复杂 UI:

function Layout({ header, sidebar, content }) {
  return (
    <div className="layout">
      <div className="header">{header}</div>
      <div className="main">
        <div className="sidebar">{sidebar}</div>
        <div className="content">{content}</div>
      </div>
    </div>
  );
}

// 使用
<Layout
  header={<Header />}
  sidebar={<Navigation />}
  content={<Article />}
/>

组件性能优化

常用优化手段:

  1. React.memo 缓存组件:

    const MemoizedComponent = React.memo(function MyComponent(props) {
    /* 使用 props 渲染 */
    });
  2. useCallback 缓存函数:

    const memoizedCallback = useCallback(() => {
    doSomething(a, b);
    }, [a, b]);
  3. useMemo 缓存计算结果:

    const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

组件测试方案

使用 Jest + Testing Library 测试组件:

import { render, screen } from '@testing-library/react';
import Button from './Button';

test('renders button with text', () => {
  render(<Button>Click</Button>);
  expect(screen.getByText('Click')).toBeInTheDocument();
});

组件文档规范

使用 PropTypes 或 TypeScript 定义组件接口:

import PropTypes from 'prop-types';

function Button({ text, onClick }) {
  return <button onClick={onClick}>{text}</button>;
}

Button.propTypes = {
  text: PropTypes.string.isRequired,
  onClick: PropTypes.func
};

或使用 TypeScript:

react如何开发组件

interface ButtonProps {
  text: string;
  onClick?: () => void;
}

function Button({ text, onClick }: ButtonProps) {
  return <button onClick={onClick}>{text}</button>;
}

标签: 组件react
分享给朋友:

相关文章

实现vue组件

实现vue组件

创建 Vue 组件 Vue 组件可以通过单文件组件(.vue 文件)或直接在 JavaScript 中定义。以下是两种常见实现方式。 单文件组件方式 单文件组件包含模板、脚本和样式三部分,适合复杂项…

react性能如何

react性能如何

React 性能特点 React 通过虚拟 DOM(Virtual DOM)和高效的 diff 算法优化性能。虚拟 DOM 减少了直接操作真实 DOM 的开销,仅在必要时更新变化的部分。React 的…

react如何衰减

react如何衰减

React 中的动画衰减效果实现 在 React 中实现衰减效果(如滚动衰减、拖动释放后的惯性滑动)通常需要结合物理动画原理或第三方动画库。以下是几种常见方法: 使用 CSS 动画和 @keyfra…

react如何调试

react如何调试

调试 React 应用的方法 使用 React Developer Tools React Developer Tools 是 Chrome 和 Firefox 的浏览器扩展,可以检查组件树、状态和…

react 如何运行

react 如何运行

运行 React 项目的步骤 安装 Node.js 确保系统已安装 Node.js(建议版本 16+),可通过官网下载并安装。安装后验证版本: node -v npm -v 创建 React 项目…

react如何重置

react如何重置

重置 React 应用的状态 使用 useState 钩子重新初始化状态变量是最直接的方法。将状态变量重置为初始值或空值即可完成重置。 const [count, setCount] = useSt…