当前位置:首页 > React

react实现组件

2026-01-26 13:24:16React

React 组件实现方法

React 组件是构建用户界面的独立模块,分为函数组件和类组件两种形式。以下是常见的实现方式:

函数组件

函数组件是最简单的 React 组件形式,使用 JavaScript/TypeScript 函数定义:

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

现代 React 开发推荐使用箭头函数和 ES6 语法:

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

类组件

类组件通过继承 React.Component 实现,支持生命周期方法和状态管理:

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

状态管理

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

react实现组件

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

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

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

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

生命周期方法

类组件可以使用完整的生命周期方法:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

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

react实现组件

import { useState, useEffect } from 'react';

function Clock() {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    const timerID = setInterval(() => tick(), 1000);
    return () => clearInterval(timerID);
  }, []);

  function tick() {
    setDate(new Date());
  }

  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );
}

组件通信

父组件通过 props 向子组件传递数据:

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

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

子组件通过回调函数向父组件通信:

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

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

function Child({ onClick }) {
  return (
    <button onClick={() => onClick('Some data')}>
      Click me
    </button>
  );
}

高阶组件

高阶组件(HOC)是接收组件并返回新组件的函数:

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

const EnhancedComponent = withLogging(MyComponent);

自定义 Hook

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

function useCounter(initialValue) {
  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(0);

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

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

相关文章

vue实现下拉框组件

vue实现下拉框组件

Vue 下拉框组件实现 基础实现 创建基础下拉框组件,使用v-model实现双向数据绑定: <template> <div class="dropdown"> &…

react如何销毁

react如何销毁

React 组件销毁的机制 在 React 中,组件的销毁通常由 React 的生命周期管理。当组件从 DOM 中移除时,React 会自动触发销毁相关的生命周期方法。以下是关键点: 组件的销毁通常…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

react 如何启动

react 如何启动

创建 React 项目 使用官方工具 create-react-app 快速初始化项目,需提前安装 Node.js(版本 ≥ 14.0.0)和 npm/yarn: npx create-react-…

如何关闭react

如何关闭react

关闭React应用的步骤 在开发或运行React应用时,可能需要关闭正在运行的开发服务器或停止应用。以下是几种常见情况的处理方法: 停止开发服务器 如果正在使用npm start或yarn star…