当前位置:首页 > 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 下拉刷新组件实现 核心思路 通过监听 touch 事件计算滑动距离,结合 CSS 过渡动画实现下拉效果,触发刷新回调。 基础实现步骤 监听 touch 事件 在组件 mounted 阶段绑定…

vue组件实现

vue组件实现

Vue 组件实现 Vue 组件是 Vue.js 的核心特性之一,允许开发者将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种常见方式: 单文件组件(SFC) 单文件组件是 Vue 中…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现 Vue组件是Vue.js的核心概念之一,允许将UI拆分为独立可复用的代码片段。组件的实现方式有多种,以下是常见的几种方法。 单文件组件(SFC) 单文件组件以.vue为后缀,将…

vue实现头像组件

vue实现头像组件

Vue 头像组件实现 基础实现 创建一个可复用的头像组件,支持图片链接或文字缩写显示: <template> <div class="avatar" :style="avata…

vue组件实现原理

vue组件实现原理

Vue 组件实现原理 Vue 组件的核心实现基于以下机制: 组件注册与模板解析 Vue 组件通过 Vue.component() 或单文件组件(.vue 文件)注册。模板会被编译成渲染函数,最终生成…

vue 实现table组件

vue 实现table组件

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