網站首頁 編程語言 正文
react-native 父函數組件調用類子組件的方法,代碼如下所示:
import React, {Component} from 'react';
import {Text, View, TouchableOpacity} from 'react-native';
// 父
let child
onRefbbb = (ref) => {
child = ref
}
clickccc = () => {
child.myName()
}
const Parent =()=> {
return(
<View>
<Child onRefaaa={onRefbbb} />
<TouchableOpacity onPress={()=>clickccc()}>
<Text>onClick</Text>
</TouchableOpacity>
</View>
)
}
export default Parent
// 子
class Child extends Component {
componentDidMount(){
this.props.onRefaaa(this)
}
myName = () =>{
alert(11111111111111)
}
render() {
return (<View></View>)
}
}
補充:下面看下React 函數式組件之父組件調用子組件的方法
前言:
最近做一個React項目,所有組件都使用了函數式組件,遇到一個父組件調用子組件方法的問題,讓我好一陣頭疼。
我們都知道,React 中子組件調用父組件方法,使用 props 傳遞過來就可以在子組件中使用。但是父組件如何調用子組件方法呢?請看下面代碼:
第一步:
在父組件中,使用 useRef 創建一個 ref
import { useRef } from 'react'
// 父組件中代碼
const FCom = () => {
const cRef = useRef(null);
return (
<div>
<ChildCom ref={cRef} />
</div>
)
}
第二步:
子組件中代碼:(使用了 forwardRef,useImperativeHandle)
import { forwardRef, useImperativeHandle } from 'react'
const ChildCom = forwardRef(({
// 這里是一些props參數
}, ref) => {
useImperativeHandle(ref, () => ({
getData: getData,
otherFun: otherFun
}))
function getData() {
// to do something
}
function otherFun() {
console.log('這是其他方法')
}
return (
<div>子組件</div>
)
})
第三步:
此時,在父組件中就可以隨心所欲的調用子組件中的方法了!
import { useRef } from 'react'
// 修改父組件中代碼
const FCom = () => {
const cRef = useRef(null);
const handleClick = () => {
cRef.current && cRef.current.getData()
}
return (
<div>
<ChildCom ref={cRef} />
</div>
)
}
原文鏈接:https://www.cnblogs.com/tlfe/p/16671868.html
相關推薦
- 2022-06-30 C語言中結構體的內存對齊規則講解_C 語言
- 2022-09-14 React?UI組件庫之快速實現antd的按需引入和自定義主題_React
- 2022-07-01 使用python實現簡單去水印功能_python
- 2023-02-14 解決React報錯React.Children.only?expected?to?receive?s
- 2021-12-01 Android之小球自由碰撞動畫示例_Android
- 2022-04-25 Pycharm下載pyinstaller報錯:You?should?consider?upgradi
- 2024-03-08 Spring bean的實例化方式之靜態工廠和實例工廠的區別
- 2022-05-06 C語言中回調函數的使用詳情_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支