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

    父组件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    import React, { useState,  useRef } from 'react';
    import { Table, Card, Button, } from 'antd';
    import ChildComp from './child';

    const FComp: React.FC<any> = (props) => {
    let child = useRef();;
    let [text,setText] = useState<string>("我是父组件");

    function onChild(){
    console.log("subMitData", child.current.childMethod());
    let childName = child.current.childMethod();
    setText(childName);
    }

    return (
    <ChildComp onRef={child} />
    <Button type='primary' onClick={onChild}>调用子组件</Button>
    <h1>{text}<h1>
    )
    }

    子组件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    import React, { useImperativeHandle} from 'react';

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


    上一篇:
    uni-app 安卓手机真机调试
    下一篇:
    微信小程序 获取元素高度(获取元素节点信息)
    本文目录
    本文目录