当前位置:首页 > 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 等属性实现。

函数式组件示例:

如何写react 组件

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>;
}

子组件向父组件传递数据

通过回调函数实现:

如何写react 组件

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 测试组件:

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 的 data 和 methods 定义倒计时逻辑,通过 setInterval 更新剩余时间。 <template> <div>{…

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

Vue 拖拽实现组件嵌套 使用 Vue 实现拖拽组件嵌套功能可以通过原生 HTML5 拖拽 API 或第三方库如 vuedraggable 实现。以下是两种方法的详细说明: 使用 HTML5 拖拽…

vue实现折叠组件

vue实现折叠组件

Vue 折叠组件实现方法 基于 v-show 和事件触发 通过 v-show 控制内容的显示与隐藏,结合点击事件切换状态。 <template> <div>…

vue哪个组件实现动画

vue哪个组件实现动画

在Vue中实现动画效果,可以通过以下组件和方法实现: Vue内置动画组件 Vue提供了<transition>和<transition-group>两个内置组件,用于处理进入…

vue穿梭框组件实现

vue穿梭框组件实现

实现 Vue 穿梭框组件的基本思路 穿梭框(Transfer)组件通常用于在两个列表之间移动数据项。核心功能包括左侧列表、右侧列表、移动按钮(左移、右移、全选等)以及数据项的渲染与交互。 基础结构…

vue组件传值实现分页

vue组件传值实现分页

Vue组件传值实现分页的方法 在Vue中实现分页功能,通常需要父子组件之间的数据传递。以下是几种常见的传值方式: 使用props传递数据 父组件通过props向子组件传递当前页码和总页数等分页信息…