当前位置:首页 > React

react组件实现

2026-01-26 15:02:28React

React 组件实现方法

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

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

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

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

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 管理内部状态:

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

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

react组件实现

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
分享给朋友:

相关文章

vue实现穿梭框树组件

vue实现穿梭框树组件

Vue 穿梭框树组件实现 穿梭框树组件通常结合了树形结构和穿梭框功能,允许用户在左右两栏之间移动树节点数据。以下是基于 Vue 的实现方案: 核心功能设计 数据结构 树形数据通常采用嵌套结构,例如:…

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app npm…

elementui组件

elementui组件

ElementUI 组件概述 ElementUI 是一套基于 Vue.js 的桌面端组件库,提供丰富的 UI 组件,适用于快速开发中后台系统。以下是其核心组件分类及典型用法。 基础组件 Button…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何遍历

react如何遍历

遍历数组或对象的方法 在React中,遍历数组或对象通常用于渲染列表或动态生成内容。以下是几种常见的遍历方法: 使用map遍历数组map是遍历数组并返回新数组的高阶函数,适合渲染列表。…

react如何encode

react如何encode

React 中编码的实现方式 在 React 中,编码通常涉及对 URL、HTML 实体或特殊字符的处理。以下是几种常见的编码方法: 使用 encodeURIComponent 进行 URL 编码…