面试题-React(六):React组件和生命周期

21 篇文章 0 订阅
20 篇文章 1 订阅

一、React组件

React组件简介:
React组件是构建用户界面的基本单元。它们将界面拆分成独立、可重用的部分,使得代码更加模块化、可维护性更高。React组件可以是函数组件或类组件,它们接收输入的数据(称为props)并返回表示用户界面的React元素。

创建React组件:
在React中,可以通过两种方式来创建组件:函数组件和类组件。下面分别介绍这两种方式的创建方法。

  1. 函数组件:
    函数组件是最简单的创建组件的方式,它是一个纯函数,接收props作为参数并返回一个React元素。函数组件适用于没有内部状态(state)或生命周期需求的简单组件。
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

在上面的例子中,Greeting是一个函数组件,它接收一个name属性作为props并返回一个包含欢迎消息的h1元素。

  1. 类组件:
    类组件是使用ES6类语法来创建的组件,它继承了React.Component类,并可以拥有内部状态和生命周期函数。类组件适用于需要状态管理或生命周期控制的复杂组件。
import React from 'react';

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

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}

在上面的例子中,Counter是一个类组件,它继承自React.Component,具有内部状态count和一个点击按钮来增加计数值的功能。

使用组件:
无论是函数组件还是类组件,都可以像HTML标签一样在其他组件的渲染函数中使用。

import React from 'react';

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

在上述例子中,App组件中使用了之前定义的Greeting函数组件和Counter类组件。

二、React生命周期

React生命周期是理解和掌握React组件的关键。通过合理地使用生命周期方法,我们可以在不同的阶段执行必要的操作,实现更精细的控制和交互。

React生命周期方法

React生命周期方法可以分为三个主要阶段:挂载阶段、更新阶段和卸载阶段。下面详细解释每个阶段及其对应的生命周期方法。

挂载阶段:
在组件被插入DOM中时调用。

  1. constructor(props):

构造函数,用于初始化组件的状态和绑定方法。通常在此阶段初始化组件的内部状态。

  1. render():

渲染方法,返回表示组件UI的React元素。必须在此方法内返回UI内容。

  1. componentDidMount():

组件挂载后调用,适合进行网络请求、DOM操作或初始化操作。此阶段常用于异步数据获取。

更新阶段:
当组件的props或state发生变化时调用。

  1. render():

更新阶段也会调用render方法来重新渲染组件的UI。

  1. componentDidUpdate(prevProps, prevState):

组件更新后调用,可在此处理DOM更新、网络请求或其他副作用操作。prevProps和prevState参数表示之前的props和state。

卸载阶段:
在组件被移除DOM时调用。

  • componentWillUnmount():

组件即将卸载时调用,适合进行清理操作,如取消网络请求、清除定时器等。

图示

React生命周期

代码示例

以下是一个使用React生命周期方法的示例,展示了生命周期方法的执行顺序和用途。

import React from 'react';

class LifecycleExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    console.log('constructor');
  }

  increment() {
    this.setState({
      count: this.state.count + 1
    })
  }

  componentDidMount() {
    console.log('componentDidMount');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate', prevProps, prevState);
  }

  componentWillUnmount() {
    console.log('componentWillUnmount');
  }

  render() {
    console.log('render');
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.increment()}>increment</button>
      </div>
    );
  }
}

class App extends React.Component {
  state = { showComponent: true };

  toggleComponent = () => {
    this.setState({ showComponent: !this.state.showComponent });
  };

  render() {
    return (
      <div>
        {this.state.showComponent && <LifecycleExample />}
        <button onClick={this.toggleComponent}>Toggle Component</button>
      </div>
    );
  }
}

export default App;

初始化

点击increment增加count

点击toggleComponent卸载组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端每日三省

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值