首页 > 技术文章 > reactHooks的组件通信

dreamtt 2022-02-25 17:01 原文

父组件调用子组件的方法

 

// 父组件

import React, { useEffect, useRef, useState } from 'react';
import StopModal from './components/stopModal';

const DirectiveStop = (props: any) => {
  const stopModalRef = useRef();

  // 点击调用子组件的方法
  const handleClick = (val) => { 
    stopModalRef.current.show(stopDisabled);
  }
  
  // 更新表格数据
  const callbackUpdate = () => {

  };
  return (
    <>
      <div>父组件</div>
      {/* 这是第一种写法 */}
      <StopModal stopModalRef={stopModalRef} callbackUpdate={callbackUpdate} />
      {/* 这是第二张写法   官方案例 */}
      <StopModal ref={stopModalRef} callbackUpdate={callbackUpdate} /> 

    </>

  );
};
export default DirectiveStop;
// 子组件

import React, { useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';


const Son = (props: any ,ref: any) => {
  const { stopModalRef, callbackUpdate } = props

  // ----------------------------------------------------------------------

  // 对应第一张方法
  const show = (val) => {
    console.log(val);
  }
  stopModalRef.current = { show }

  // ----------------------------------------------------------------------
  // 对应的第二张方法
  useImperativeHandle(ref, () => ({
    show(val) {
      console.log(val);
    }
  }))

  return (
    <>
      <div>子组件</div>
    </>
  );
};
export default Son;  // 对应的第一种写法 
// export default forwardRef(Son)  // 对应的第二种写法,必须是要 forwardRef 包裹住

 

推荐阅读