本文主要是介绍Hooks 「 useImperativeHandle 」子组件向父组件暴露方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
封装公共的组件提供操作方法。
子组件
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react'const PublicOffice = ({ PublicOfficeRef }) => {const pathList = useRef([{ file: '', name: '', year: 2022 }])// 向父组件暴露的方法useImperativeHandle(PublicOfficeRef, () => ({// getVal 就是暴露给父组件的方法getVal: () => pathList?.current,}))return (<div></div>)}export default PublicOffice
父组件
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react'const TabSonDom = () => {const PublicOfficeRef = useRef(null)const btnSave = () => {console.log(PublicOfficeRef,'PublicOfficeRef');console.log(PublicOfficeRef?.current?.getVal(),'PublicOfficeRef.current?.getVal(');}return (<div><PublicOffice PublicOfficeRef={PublicOfficeRef}/><Button onClick={()=>btnSave()}> 保存 </Button></div>)
}
export default PublicOffice
这篇关于Hooks 「 useImperativeHandle 」子组件向父组件暴露方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!