当前位置:首页 > React

react组件实现

2026-01-26 15:02:28React

React 组件实现方法

React 组件是构建用户界面的基本单元,分为函数组件和类组件两种形式。以下介绍常见的实现方式:

函数组件 函数组件是使用 JavaScript 函数定义的组件,简洁高效:

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

类组件 类组件通过 ES6 class 定义,包含生命周期方法:

react组件实现

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

Props 使用 组件通过 props 接收外部数据:

function Greeting(props) {
  return <p>Welcome, {props.userName}</p>;
}
// 使用
<Greeting userName="Alice" />

State 管理 类组件中使用 state 管理内部状态:

react组件实现

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };
  render() {
    return (
      <button onClick={this.increment}>
        Count: {this.state.count}
      </button>
    );
  }
}

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

import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

组件组合 通过组合简单组件构建复杂 UI:

function App() {
  return (
    <div>
      <Welcome name="Alice" />
      <Welcome name="Bob" />
    </div>
  );
}

生命周期方法 类组件中可使用生命周期方法:

class Clock extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(() => this.tick(), 1000);
  }
  componentWillUnmount() {
    clearInterval(this.timerID);
  }
  tick() {
    this.setState({ date: new Date() });
  }
  render() {
    return <div>Time: {this.state.date.toLocaleTimeString()}</div>;
  }
}

最佳实践 保持组件小型化且功能单一 使用 PropTypes 进行类型检查 优先使用函数组件和 Hooks 合理拆分容器组件和展示组件

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

相关文章

react 如何引入css

react 如何引入css

在 React 中引入 CSS 的方法 React 提供了多种引入 CSS 的方式,可以根据项目需求选择合适的方法。以下是常见的几种方式: 内联样式 内联样式直接在组件中通过 style 属性定义,…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 基础页面结构 在 s…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react如何配置

react如何配置

配置React项目的基本步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过命令行检查版本: node -v npm -v 创建React项目 使用官方工具Creat…

react组件如何通讯

react组件如何通讯

React 组件通讯方式 React 组件间的通讯方式主要包括以下几种方法,适用于不同场景下的数据传递和状态管理需求。 父子组件通讯(Props 传递) 父组件通过 props 向子组件传递数据或回…

react如何建项目

react如何建项目

创建React项目的几种方法 使用官方工具Create React App(CRA) npx create-react-app my-app 这条命令会创建一个名为my-app的新React项目,包含…