react函数组件+ts 使用useImperativeHandle和forwardRef将子组件的方法或者实例传给父组件

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'/>
    </>
    )
}

猜你喜欢

转载自blog.csdn.net/weixin_44441196/article/details/108074132#comments_26735699