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

相关文章

vue实现多级组件

vue实现多级组件

实现多级组件的基本结构 在Vue中实现多级组件通常涉及父子组件嵌套,通过props向下传递数据,通过$emit向上传递事件。多级组件的核心是递归或动态组件渲染。 <!-- 父组件 Parent…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &l…

react native如何启动

react native如何启动

React Native 启动步骤 确保已安装 Node.js(建议版本 14 或更高)和 npm/yarn。安装完成后,通过命令行工具执行以下操作。 初始化新项目 使用 React Native…

如何评价react native

如何评价react native

React Native 的优势 跨平台开发效率高 React Native 允许开发者使用 JavaScript 和 React 编写代码,同时生成 iOS 和 Android 应用,大幅减少开发成…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment 包。确保项目中已安装 moment.js,因为 react-moment 依赖它。 npm instal…

如何降低react版本

如何降低react版本

降低 React 项目版本的步骤 检查当前 React 版本 在项目根目录的 package.json 文件中查看 dependencies 或 devDependencies 下的 react 和…