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

react 父子组件通信

一、父组件向子组件通信

1. 原理

父组件可以将数据、函数或其他 JavaScript 对象作为`props`传递给子组件,子组件通过`props`接收并使用这些信息。

2. 示例

父组件传递 message 给子组件。

import { useState } from "react";

import ChildComponent from "./ChildComponent";



const ParentComponent = () => {

  const [message, setMessage] = useState("Hello from Parent");

  return (

    <div>

      <ChildComponent message={message} />

    </div>

  );

};

子组件通过`props`接收`message`。

const ChildComponent = (props) => {

  return (

    <div>

      <p>{props.message}</p>

    </div>

  );

};

二、子组件向父组件通信

1. 原理

父组件将一个函数作为`props`传递给子组件

2. 示例

点击子组件按钮传递消息给父组件。

import { useState } from "react";

import ChildComponent from "./ChildComponent";



const ParentComponent = () => {

  const [childMessage, setChildMessage] = useState("");

  const receiveMessageFromChild = (message) => {

    setChildMessage(message);

  };

  return (

    <div>

      <ChildComponent sendMessageToParent={receiveMessageFromChild} />

      <p>Message from child: {childMessage}</p>

    </div>

  );

};

在子组件中,通过调用从父组件接收的函数来传递数据。

const ChildComponent = (props) => {

  const handleClick = () => {

    const message = "Hello from Child";

    props.sendMessageToParent(message);

  };

  return (

    <div>

      <button onClick={handleClick}>Send Message to Parent</button>

    </div>

  );

};


http://www.kler.cn/a/420373.html

相关文章:

  • 【Qt】QDateTimeEdit控件实现清空(不保留默认时间/最小时间)
  • Pytorch使用手册- TorchVision目标检测微调Tutorial的使用指南(专题十二)
  • bash命令缓存导致命令执行失败的问题
  • 插入数据如何确保redis与数据库同步 详解
  • 单链表---链表分割
  • 基于米尔全志T527开发板的FacenetPytorch人脸识别方案
  • 【C++】深入解析 using namespace std 语句
  • npm error code ETIMEDOUT 简单排查
  • 双向长短期记忆(Bi-LSTM)神经网络介绍
  • Linux - 前端程序员常用的 Linux 命令
  • LearnOpenGL学习(光照 -- 投光物,多光源)
  • 在云上怎么样让环境更加安全?
  • SQLAlchemy
  • Spring,SpringMVC,SpringBoot,SpringCloud有什么区别和联系?
  • 汽车操作系统详解
  • dhcpd服务器的配置与管理(超详细!!!)
  • 贝叶斯统计的核心思想与基础知识:中英双语
  • 含k个3的数
  • 产品转后端?
  • 使用 Docker 部署 Spring Boot 项目流程