react ref转发+useimperativehandle写法

应用场景:父组件需要子组件的一些方法

代码:

父组件:

import React from "react";
import Child from '../components/child'
type stateTypes = {};
type propsTypes = {};
const childRef = React.createRef<any>();//这里创建一个给子组件的ref类型暂时不知道写什么就写any先,有知道的大佬麻烦告诉下类型
class Index extends React.Component<propsTypes, stateTypes> {
  constructor(props: any) {
    super(props);
    this.state = {};
  }
  handleClick(){
    console.log(childRef);
    childRef.current.test();//通过current调用暴露的方法
  }
  render() {
    return <div>
      <button onClick={this.handleClick}>点我</button>
      <Child ref={childRef}></Child>
    </div>;
  }
}
export default Index;

子组件:

import React, { useImperativeHandle } from "react";

const Child = React.forwardRef((props: any, ref: any) => {
  //这里的ref就是父组件传递来的ref,子组件使用myref属性接受
  return <ChildComp {...props} myRef={ref}></ChildComp>;
});
function ChildComp(props: any) {
  const { myRef } = props;
  const test = () => {
    console.log("hello");
  };
  //第一个参数就是父组件的ref,第二个参数就是要返回暴露给调用者的属性或者方法
  useImperativeHandle(myRef, () => {
    //也可以写成 ()=>({JSON对象})
    return{
      test,
    }
  });
  return (
    <div>
      <span></span>
    </div>
  );
}

export default Child;

猜你喜欢

转载自www.cnblogs.com/llcdbk/p/13403589.html