当前位置:首页 > 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
分享给朋友:

相关文章

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何发音

react如何发音

React的发音 React的正确发音为 /riˈækt/,类似于“ree-akt”。以下是详细说明: 发音分解 第一个音节“Ree”发音类似英文单词“see”中的“ee”音。 第二个音节…

react就业如何

react就业如何

React 就业市场现状 React 作为当前主流前端框架之一,就业需求持续旺盛。国内外互联网企业、中大型公司以及初创团队普遍采用 React 技术栈,尤其在 Web 应用、移动端(React Nat…

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

react如何通信

react如何通信

React 组件通信方式 React 组件间的通信方式多样,具体选择取决于组件关系和场景需求。以下是常见方法: 父子组件通信 父组件通过 props 向子组件传递数据,子组件通过回调函数通知父组件…