封装公共的组件提供操作方法。
子组件
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