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

  • Post author:
  • Post category:其他




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



版权声明:本文为weixin_44441196原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。