当前位置:首页 > React

如何写react 组件

2026-01-24 06:10:06React

创建 React 组件的基本方法

React 组件可以通过函数式组件或类组件两种方式创建。以下是具体实现方法:

函数式组件

函数式组件是当前推荐的方式,简洁且支持 Hooks。

import React from 'react';

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

export default Greeting;

如果使用箭头函数:

const Greeting = ({ name }) => <h1>Hello, {name}</h1>;

类组件

类组件是传统方式,适用于需要生命周期方法或状态的场景。

import React, { Component } from 'react';

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

export default Greeting;

组件状态管理

函数式组件使用 useState Hook 管理状态:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

类组件通过 this.statethis.setState 管理状态:

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

处理事件

在 React 中,事件处理通过 onClickonChange 等属性实现。

函数式组件示例:

function Button() {
  const handleClick = () => {
    alert('Button clicked!');
  };

  return <button onClick={handleClick}>Click Me</button>;
}

类组件示例:

class Button extends Component {
  handleClick = () => {
    alert('Button clicked!');
  };

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}

组件生命周期(类组件)

类组件提供生命周期方法,如 componentDidMountcomponentDidUpdate 等。

class LifecycleExample extends Component {
  componentDidMount() {
    console.log('Component mounted');
  }

  componentDidUpdate() {
    console.log('Component updated');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <div>Lifecycle Example</div>;
  }
}

函数式组件使用 useEffect 替代生命周期:

import React, { useEffect } from 'react';

function LifecycleExample() {
  useEffect(() => {
    console.log('Component mounted or updated');
    return () => console.log('Component will unmount');
  }, []); // 空数组表示仅在挂载和卸载时运行
}

组件间通信

父组件向子组件传递数据

通过 props 传递数据:

function Parent() {
  return <Child message="Hello from Parent" />;
}

function Child({ message }) {
  return <p>{message}</p>;
}

子组件向父组件传递数据

通过回调函数实现:

function Parent() {
  const handleChildClick = (data) => {
    console.log('Data from child:', data);
  };

  return <Child onClick={handleChildClick} />;
}

function Child({ onClick }) {
  return <button onClick={() => onClick('Child data')}>Send Data</button>;
}

使用 Context 跨组件共享数据

创建 Context 并在组件中使用:

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  return <ThemedButton />;
}

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button style={{ background: theme === 'dark' ? '#333' : '#FFF' }}>Themed Button</button>;
}

组件样式

内联样式

通过 style 属性直接设置:

function StyledComponent() {
  return <div style={{ color: 'red', fontSize: '20px' }}>Styled Text</div>;
}

CSS 模块

使用 CSS 模块实现局部作用域样式:

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

function Button() {
  return <button className={styles.button}>Styled Button</button>;
}

第三方库(如 styled-components)

通过 styled-components 实现动态样式:

import styled from 'styled-components';

const StyledButton = styled.button`
  background: ${props => props.primary ? 'blue' : 'gray'};
  color: white;
`;

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

组件优化

使用 React.memo 避免不必要的渲染

const MemoizedComponent = React.memo(function MyComponent(props) {
  return <div>{props.value}</div>;
});

使用 useCallbackuseMemo 优化性能

import React, { useCallback, useMemo } from 'react';

function OptimizedComponent() {
  const memoizedCallback = useCallback(() => {
    console.log('Callback optimized');
  }, []);

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

  return <button onClick={memoizedCallback}>Click</button>;
}

组件测试

使用 Jest 和 React Testing Library 测试组件:

如何写react 组件

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

test('renders greeting message', () => {
  render(<Greeting name="World" />);
  expect(screen.getByText('Hello, World')).toBeInTheDocument();
});

通过以上方法,可以高效地创建和管理 React 组件,满足不同场景的需求。

标签: 组件如何写
分享给朋友:

相关文章

vue如何实现目录组件

vue如何实现目录组件

实现目录组件的基本思路 在Vue中实现目录组件通常需要结合页面内容的结构化数据(如标题层级),通过动态渲染生成可交互的目录。核心步骤包括提取标题、生成目录结构、实现滚动联动等。 提取标题信息 通过d…

vue table组件实现

vue table组件实现

Vue 表格组件实现方案 基础表格实现 使用<table>标签结合v-for指令渲染数据是最简单的实现方式: <template> <table> &…

vue 实现table组件

vue 实现table组件

Vue 实现 Table 组件 基础表格结构 使用 Vue 的模板语法构建表格的基本框架,通过 v-for 动态渲染数据。 <template> <table>…

vue实现动态组件

vue实现动态组件

动态组件的基本概念 在Vue中,动态组件允许根据条件或用户交互切换不同的组件,无需重复编写模板逻辑。核心是通过<component>标签的is属性绑定组件名或组件对象。 使用is属性切换…

vue实现loading组件

vue实现loading组件

Vue 实现 Loading 组件的方法 基础实现方案 创建一个独立的 Loading.vue 组件文件: <template> <div v-if="isLoading" c…

vue 实现 拖拽组件

vue 实现 拖拽组件

Vue 实现拖拽组件的方法 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 dr…