当前位置:首页 > React

react如何实现组件

2026-02-11 17:09:34React

React 组件实现方法

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

函数组件实现

函数组件是推荐使用的现代写法,通过纯函数定义:

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

箭头函数写法更简洁:

const Greeting = (props) => <h1>Hello, {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>
  );
}

类组件实现

传统类组件写法需要继承 React.Component:

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

带状态的类组件:

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

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <button onClick={this.handleClick}>
        Clicked {this.state.count} times
      </button>
    );
  }
}

组件组合方式

组件可以嵌套组合使用:

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

组件间通信

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

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

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

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

function Parent() {
  const handleChildClick = (msg) => {
    console.log(msg);
  };
  return <Child onClick={handleChildClick} />;
}

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

生命周期管理

函数组件使用 useEffect 处理生命周期:

import { useEffect } from 'react';

function Timer() {
  useEffect(() => {
    const timer = setInterval(() => console.log('tick'), 1000);
    return () => clearInterval(timer); // 清理函数
  }, []);
  return <div>Timer is running</div>;
}

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

react如何实现组件

class Timer extends React.Component {
  componentDidMount() {
    this.timer = setInterval(() => console.log('tick'), 1000);
  }

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

  render() {
    return <div>Timer is running</div>;
  }
}

分享给朋友:

相关文章

vue实现组件封装

vue实现组件封装

Vue 组件封装方法 封装组件的基本步骤 创建独立的 .vue 文件,包含 template、script 和 style 三个部分。通过 props 接收父组件传递的数据,使用 $emit 触发自…

vue如何实现记住我

vue如何实现记住我

实现“记住我”功能的步骤 在Vue中实现“记住我”功能通常涉及前端保存用户登录状态(如token)到本地存储,并在下次访问时自动恢复登录状态。以下是具体实现方法: 使用localStorage或co…

php如何实现直播

php如何实现直播

实现直播功能的方法 PHP可以通过结合其他技术和工具来实现直播功能。以下是几种常见的方法: 使用流媒体服务器 配置流媒体服务器如Nginx-RTMP、Red5或Wowza。这些服务器支持RTMP协…

java如何实现多线程

java如何实现多线程

实现多线程的方法 在Java中,实现多线程主要有两种方式:继承Thread类和实现Runnable接口。此外,还可以使用ExecutorService等高级工具类来管理线程。 继承Thread类 通…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性来完成。以下是几种常见的实…

如何缓存react组件

如何缓存react组件

缓存React组件的方法 React.memo 使用React.memo对函数组件进行浅比较缓存,避免不必要的重新渲染。适用于props不变的场景。 const MemoizedComponen…