当前位置:首页 > React

react 组件实现

2026-01-26 12:15:20React

React 组件实现方式

React 组件是构建用户界面的核心单元,主要分为函数组件和类组件两种形式。以下是具体实现方法:

函数组件实现

函数组件是使用 JavaScript 函数定义的组件,简洁且易于理解:

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

箭头函数写法:

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

类组件实现

类组件通过 ES6 的 class 定义,可以包含状态和生命周期方法:

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

组件状态管理

函数组件中使用 Hooks 管理状态:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

类组件中使用 state 对象:

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

  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Clicked {this.state.count} times
      </button>
    );
  }
}

组件生命周期

类组件中可以使用的生命周期方法示例:

react 组件实现

class Example extends React.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 { useEffect } from 'react';

function Example() {
  useEffect(() => {
    console.log('Component mounted');
    return () => console.log('Component will unmount');
  }, []);

  return <div>Lifecycle Example</div>;
}

组件间通信

父组件向子组件传递 props:

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

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

子组件向父组件传递数据:

function Parent() {
  const handleData = (data) => {
    console.log('Received:', data);
  };
  return <Child onSendData={handleData} />;
}

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

组件样式处理

内联样式:

react 组件实现

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

CSS Modules:

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

function StyledComponent() {
  return <div className={styles.container}>Styled Text</div>;
}

Styled Components:

import styled from 'styled-components';

const StyledDiv = styled.div`
  color: red;
  font-size: 20px;
`;

function StyledComponent() {
  return <StyledDiv>Styled Text</StyledDiv>;
}

高阶组件实现

高阶组件(HOC)是用于组件逻辑复用的高级技术:

function withLogging(WrappedComponent) {
  return function(props) {
    console.log('Rendering:', WrappedComponent.name);
    return <WrappedComponent {...props} />;
  };
}

const EnhancedComponent = withLogging(MyComponent);

自定义 Hook 实现

自定义 Hook 可以提取组件逻辑以便复用:

function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);
  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);
  return { count, increment, decrement };
}

function Counter() {
  const { count, increment } = useCounter();
  return <button onClick={increment}>{count}</button>;
}

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

相关文章

如何评价react native

如何评价react native

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

如何降低react版本

如何降低react版本

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

react如何

react如何

React 基础概念 React 是一个用于构建用户界面的 JavaScript 库,专注于组件化开发。通过虚拟 DOM 和高效的渲染机制,React 能够实现高性能的 UI 更新。 安装 Re…

vue实现广告组件

vue实现广告组件

Vue 实现广告组件的核心方法 数据驱动的广告内容渲染 通过 props 接收广告数据(如图片URL、跳转链接等),使用 v-bind 动态绑定属性。典型结构包含 <a> 标签嵌套 <…

vue怎么实现组件缓存

vue怎么实现组件缓存

vue实现组件缓存的方法 在Vue中实现组件缓存可以通过内置的<keep-alive>组件完成,该组件能够缓存不活动的组件实例,避免重复渲染。 使用<keep-alive>基…

vue穿梭框组件实现

vue穿梭框组件实现

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