当前位置:首页 > 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. 内联样式

    react如何开发组件

    <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 缓存组件:

    react如何开发组件

    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:

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

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

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

相关文章

react native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: node…

如何评价react native

如何评价react native

React Native 的优势 跨平台开发效率高:基于 JavaScript 和 React 语法,可同时开发 iOS 和 Android 应用,减少重复代码量。性能接近原生:通过原生组件渲染,性能…

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impo…

如何降低react版本

如何降低react版本

降低 React 项目版本的步骤 检查当前 React 版本 运行以下命令查看项目中安装的 React 当前版本: npm list react 或 yarn list react 修…

react如何拓展

react如何拓展

React 拓展方法 使用高阶组件(HOC) 高阶组件是一种复用组件逻辑的方式,通过接收一个组件并返回一个新组件实现功能拓展。例如,为组件添加日志功能: function withLogging…