react ref轉發+useimperativehandle寫法
阿新 • • 發佈:2020-07-30
應用場景:父元件需要子元件的一些方法
程式碼:
父元件:
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;