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;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM