欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TS函数组件中父组件调用子组件

程序员文章站 2022-07-02 22:13:43
...

需要用的api

forwardRef && useImperativeHandle

父组件

import React, { useRef } from 'react';
import { Button } from 'antd';

import Child from './Children';

interface ReturnVoid {
  getValues: () => void
}

const ForwordRef: React.FC<any> = () => {

  const childRef = useRef<ReturnVoid>(null);

  const onBtnClick = () => {
    if (childRef && childRef.current) {
      const text = childRef.current.getValues();
      console.log(text);
    }
  }
  return (
    <>
      <Button type="primary" onClick={() => { onBtnClick() }}>调用子组件方法</Button>

      <Child ref={childRef} />
    </>
  )
}

export default ForwordRef;

子组件

import React, { forwardRef, useImperativeHandle } from 'react';

// ref必须
const ForwordRef = (props: any, ref: any) => {

  useImperativeHandle(ref, () => ({
    getValues: () => {
      return ('hell word')
    }
  }))

  return (
    <>
      <p>我是子组件</p>
    </>
  )
}

export default forwardRef(ForwordRef);

TS函数组件中父组件调用子组件

相关标签: 大前端-React