当前位置: 首页 > article >正文

react的组件的概念和使用

在这里插入图片描述

文章目录

    • 1. **组件的定义**
        • **函数组件**
        • **类组件**
    • 2. **组件的生命周期**
    • 3. **状态管理**
        • **类组件中的状态管理**
        • **函数组件中的状态管理**
    • 4. **组件之间的通信**
        • **通过 Props 传递数据**
        • **上下文(Context)**
    • 5. **组件的样式**
    • 6. **处理表单**
    • 7. **错误边界**


React 组件的核心概念,包括组件的定义、生命周期、状态管理、以及如何进行组件之间的通信。以下是对 React 组件的详细解释:

1. 组件的定义

函数组件

函数组件是最简单的组件类型,它是一个 JavaScript 函数,接受 props 作为参数,并返回一个 React 元素(通常是 JSX)。

示例:

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

使用:

<Welcome name="Alice" />

案例:

function Button() {
  return <button>Click me2</button>;
}

function App() {
  const handleClick = (event) => {
    console.log(event.target);
  };

  return (
    <div className="App">
       <button onClick={handleClick}>Click me1</button>
       <Button />
    </div>
   
  ) 
}

类组件

类组件是一个 ES6 类,继承自 React.Component。它需要实现一个 render 方法,返回一个 React 元素。类组件通常用于需要状态管理和生命周期方法的场景。

示例:

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

使用:

<Welcome name="Alice" />

2. 组件的生命周期

类组件有生命周期方法,这些方法在组件的不同阶段自动调用。常见的生命周期方法包括:

  • componentDidMount:组件挂载到 DOM 后调用。通常用于数据加载。
  • componentDidUpdate:组件更新后调用。可以用于对组件更新后的处理。
  • componentWillUnmount:组件卸载前调用。用于清理操作,如移除事件监听器。

示例:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log('Component did mount!');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('Component did update!');
  }

  componentWillUnmount() {
    console.log('Component will unmount!');
  }

  render() {
    return <div>My Component</div>;
  }
}

3. 状态管理

组件可以有自己的状态(state),这是用于存储组件内部数据的对象。状态通常在类组件中通过 this.statethis.setState 来管理,而在函数组件中则通过 useState 钩子来管理。

类组件中的状态管理

示例:

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

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

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}
函数组件中的状态管理

示例:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

4. 组件之间的通信

React 组件之间可以通过 props 和上下文(Context)来进行通信。

通过 Props 传递数据

父组件可以通过 props 将数据传递给子组件。

父组件示例:

function ParentComponent() {
  return <ChildComponent message="Hello from Parent" />;
}

子组件示例:

function ChildComponent(props) {
  return <p>{props.message}</p>;
}
上下文(Context)

上下文允许组件通过树状结构传递数据,而不必逐层传递 props。你可以使用 React.createContext 创建上下文,使用 Provider 组件提供数据,使用 Consumer 组件接收数据,或者使用 useContext 钩子在函数组件中使用上下文数据。

上下文创建与使用示例:

// 创建上下文
const MyContext = React.createContext();

// 提供上下文
function MyProvider({ children }) {
  const [value, setValue] = useState('Default Value');

  return (
    <MyContext.Provider value={value}>
      {children}
    </MyContext.Provider>
  );
}

// 消费上下文
function MyConsumer() {
  const contextValue = useContext(MyContext);
  return <p>Context Value: {contextValue}</p>;
}

// 使用
function App() {
  return (
    <MyProvider>
      <MyConsumer />
    </MyProvider>
  );
}

5. 组件的样式

你可以通过几种方式给组件添加样式:

  • 内联样式:使用 JavaScript 对象作为 style 属性。

示例:

function StyledComponent() {
  const style = { color: 'blue', fontSize: '20px' };
  return <div style={style}>This is a styled component</div>;
}
  • CSS 类名:使用 className 属性来应用 CSS 类。

示例:

// CSS 文件 (styles.css)
.my-style {
  color: red;
  font-size: 18px;
}

// 组件
function StyledComponent() {
  return <div className="my-style">This is a styled component</div>;
}
  • CSS 模块:使用 CSS 模块来避免样式冲突。

示例:

// CSS 模块 (styles.module.css)
.myStyle {
  color: green;
  font-size: 16px;
}

// 组件
import styles from './styles.module.css';

function StyledComponent() {
  return <div className={styles.myStyle}>This is a styled component</div>;
}

6. 处理表单

表单可以使用受控组件来管理输入。受控组件将表单元素的值与组件的状态同步。

示例:

class ControlledForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { inputValue: '' };
  }

  handleChange = (event) => {
    this.setState({ inputValue: event.target.value });
  };

  handleSubmit = (event) => {
    alert('Submitted value: ' + this.state.inputValue);
    event.preventDefault();
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Input:
          <input type="text" value={this.state.inputValue} onChange={this.handleChange} />
        </label>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

7. 错误边界

错误边界是 React 16 引入的一个特性,用于捕获子组件树中的 JavaScript 错误,并展示备用 UI。

示例:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error('Error caught by Error Boundary:', error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

// 使用 Error Boundary
function App() {
  return (
    <ErrorBoundary>
      <SomeComponent />
    </ErrorBoundary>
  );
}

您好,我是肥晨。
欢迎关注我获取前端学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。


http://www.kler.cn/news/312318.html

相关文章:

  • 家庭聚餐:用白酒传递亲情与温暖
  • 滚雪球学SpringCloud[4.2讲]: Zuul:Netflix API Gateway详解
  • 浅谈vue2.0与vue3.0的区别(整理十六点)
  • npm run build报Cannot find module错误的解决方法
  • 誉龙视音频 Third/TimeSyn 远程命令执行复现
  • weblogic CVE-2020-14882 靶场攻略
  • 【百日算法计划】:每日一题,见证成长(018)
  • pytorch使用技巧
  • Designify——AI优化图像设计,自动去背景、调整构图、添加视觉效果,创建高质量的设计图像
  • 2024 Oracle CloudWorld的信息量实在太大了
  • Pikachu靶场之XSS
  • Leetcode面试经典150题-97.交错字符串
  • 记一次kafka消息丢失问题排查
  • [SDX35+WCN6856]SDX35 + WCN6856 WiFi可以up起来之后无法扫描到SSID
  • 7.sklearn-逻辑回归、精确率和召回率、ROC曲线和AUC指标
  • Java项目: 基于SpringBoot+mybatis+maven旅游管理系统(含源码+数据库+毕业论文)
  • nvm node管理工具常用指令
  • 编程基础:函数栈帧的创建和销毁
  • (十六)Ubuntu 20.04 下搭建PX4+MATLAB 仿真环境(HITL)
  • 无人机之AI跟踪篇
  • Facebook直播限流是什么原因?是ip地址导致的吗
  • Java商城的技术优势有哪些
  • Spring 出现 No qualifying bean of type ‘com.xxx‘ available 解决方法
  • 35.贪心算法2
  • [ffmpeg] 视频格式转换
  • 开发板与ubuntu建立网络通信(NFS和TFTP协议搭建)
  • elasticsearch实战应用
  • NAT网络地址转换
  • 【spring】spring框架中使用的设计模式有哪些,经典的设计模式应用,spring框架中哪些地方使用了哪些优秀的设计模式
  • 制作炫酷个人网页:用 HTML 和 CSS3 展现你的风格