react函数组件+ts 使用useImperativeHandle和forwardRef
**
子组件 (传方法)
import React, {
useImperativeHandle, forwardRef } from 'react';
const Child = forwardRef((props: any,ref: any) => {
let {
test='其他参数'} = props
useImperativeHandle(ref, () => ({
getData
}))
const getData = () => {
// to do something
}
return (
<div>子组件</div>
)
})
export {
Child}
子组件 (传实例)
import React, {
forwardRef } from 'react';
const Child = forwardRef((props: any, ref: any) => {
let {
test='其他参数' } = props
return (
<div ref={
ref }>子组件</div>
)
})
export {
Child}
父组件(传方法)
import React, {
useContext, useState,useRef } from 'react';
import {
Child} form './child'
export function Detail(){
const ref = useRef(null)
return (
<>
<Child ref={
ref} test='123'/>
<div onClick={
()=>{
ref.current.getData()}}></div>
</>
)
}
父组件(传实例)
import React, {
useContext, useState } from 'react';
import {
Child} form './child'
export function Detail(){
const ref = React.createRef();
return (
<>
<Child ref={
ref} test='123'/>
</>
)
}