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

React 子组件调用父组件的方法,以及互相传递数据

<script type="text/babel" data-type="module">
import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';const ParentComponent = () => {const [message, setMessage] = useState("")//父组件方法,将传递给子组件const handleChildAction = (childMessage) => {setMessage(childMessage)  //效果是接收子组件传来的数据,并修改state}const parentMessage = "Hello I'm a parent component" //传递给子组件的数据return (<div style={{padding: '20px', border: '1px solid Red', width: '400px'}}><p>父组件</p><ChildComponent onAction={handleChildAction} fromParent={parentMessage} /><p>来自子组件的消息:{message}</p></div>)
}const ChildComponent = ({onAction, fromParent}) => {//子组件的方法,效果是调用传递过来的父组件方法,并且修改stateconst handleClick = () => {onAction('我是子组件的消息,我收到了你的消息:' + fromParent)}return (<div style={{padding: '20px', border: '1px solid black', width: '300px'}}><p>子组件</p><button onClick={handleClick}>发送消息给父组件</button></div>)
}const root = createRoot(document.getElementById('root'));
root.render(<StrictMode><ParentComponent /></StrictMode>
);
</script>

需要注意的是,如果是TypeScript,需要指定参数的类型是方法

interface ChildComponentProps {onAction: (message: string) => void; 
}const ChildComponent: React.FC<ChildComponentProps> = ({ onAction }) => {

效果:

点击子组件的按钮后:

http://www.lryc.cn/news/462146.html

相关文章:

  • 爬虫基础---python爬虫系列2
  • jmeter在beanshell中使用props.put()方法的注意事项
  • 息肉检测数据集 yolov5 yolov8适用于目标检测训练已经调整为yolo格式可直接训练yolo网络
  • 通过API进行Milvus实例配置
  • Excelize 开源基础库 2.9.0 版本正式发布
  • 人脸识别-特征算法
  • C++【内存管理】(超详细讲解C++内存管理以及new与delete的使用和原理)
  • elementUi el-table 表头高度异常问题
  • kubekey的应用
  • 如何识别并分类转录因子的家族
  • 【C++11】可变模板参数详解
  • 本地群晖NAS安装phpMyAdmin管理MySQ数据库实战指南
  • QTableWidget 接口详情
  • GESP CCF python四级编程等级考试认证真题 2024年9月
  • oracle数据库名实例名服务名
  • python+appium+雷电模拟器安卓自动化及踩坑
  • Python第七八次作业
  • Leetcode——数组:螺旋矩阵59.螺旋矩阵
  • C++类与对象-继承和多态(超全整理)
  • 3.3 Thymeleaf语法
  • 使用Dlib库实现人脸检测和关键点定位
  • DNS隧道流量分析
  • HCIP-HarmonyOS Application Developer 习题(十一)
  • 使用Ollama测试OpenAI的Swarm多智能体编排框架
  • C# 完美操作 Active Directory 详细总结,轻松玩转域管理
  • PCL 点云配准 KD-ICP算法(精配准)
  • uniapp打包安卓apk步骤
  • Springboot 整合 Java DL4J 实现安防监控系统
  • 【数据结构与算法】第1课—算法复杂度
  • 利用高德API获取整个城市的公交路线并可视化(五)