当前位置:首页 > 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 组件实现方法 单文件组件 (SFC) 使用 .vue 文件格式,包含模板、脚本和样式三部分: <template> <div class="example">{{…

vue 实现组件刷新

vue 实现组件刷新

实现组件刷新的方法 在Vue中,组件刷新通常指重新渲染组件或重置组件状态。以下是几种常见的实现方式: 使用v-if控制渲染 通过v-if指令可以销毁并重新创建组件: <template>…

vue实现下拉框组件

vue实现下拉框组件

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

如何选购react

如何选购react

选购 React 相关产品或服务的建议 React 是一个用于构建用户界面的 JavaScript 库,广泛应用于前端开发。以下是选购 React 相关产品(如课程、书籍、工具、组件库等)的参考方法:…

如何下载react

如何下载react

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

react如何查

react如何查

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