zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    UVALive4727:jump
    UVALive
    UVA11795 Mega Man's Mission
    UVA4731:Cellular Network
    UVA11404:Palindromic Subsequence
    设计思路
    阅读计划
    上课未完成代码原因
    《人月神话》读后感
    《软件工程》第十一章总结
  • 原文地址:https://www.cnblogs.com/llcdbk/p/13403589.html
Copyright © 2011-2022 走看看