React Hooks+Typescript 中 父组件调用子组件方法.

父组件

import React, { useState,  useRef } from 'react';
import { Table, Card, Button, } from 'antd';
import ChildComp from './child';

const FComp: React.FC = (props) => {
    let child = useRef();;
    let [text,setText] = useState("我是父组件");
    
    function onChild(){
        console.log("subMitData", child.current.childMethod());
        let childName = child.current.childMethod();
        setText(childName);
    }
    
    return (
            
            
            

{text}

) }

子组件

import React, { useImperativeHandle} from 'react';

const ChildComp: React.FC = (props:{onRef}) => {
     useImperativeHandle(onRef, () => ({
        // onChild 就是暴露给父组件的方法
        onChild: () => {
          return {
            childName:'我是子组件'
          }
        }
    }));
    return (
        
我是子组件
)

你可能感兴趣的:(React Hooks+Typescript 中 父组件调用子组件方法.)