react hooks 父组件通过ref获取子组件的变量和方法

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

const Child: React.FC<any> = forwardRef((props, ref) => {
  
  const [childText, setChildText] = useState<number>(1);

  const childAbc = () => {
    console.log('childAbc');
  };

  // 把实例传给ref,然后父组件可以通过ref获取子组件的变量和方法。
  useImperativeHandle(ref, () => ({
    childAbc,
    childText,
    setChildText,
  }));

  return (
    <div className="intelligenceSearch">
      子组件
      childIndex -变化了 {childText}
    </div>
  );
});

const Father: React.FC<any> = (props) => {
  // 获取子组件的实例和方法
  let childRef = useRef<any>(null);

  return (
    <div className="intelligenceSearch">
      父组件
      <Button onClick={()=>{
        let {childText, setChildText}: {childText: number; setChildText: Function} = childRef.current;
        setChildText(childText+1)
      }}>改变childText的值</Button>

      <Button onClick={() => {
        const {childAbc} = childRef.current;
        childAbc && childAbc();
      }}>执行子组件childAbc方法</Button>

      ----------
      <Child ref={childRef} />
    </div>
  );
};

export default Father;

 

posted @ 2022-04-14 09:50  本溢  阅读(1051)  评论(0)    收藏  举报