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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM