zoukankan      html  css  js  c++  java
  • react高阶组件+ref转发的组合使用

    增强组件:
    import React from "react"; type propsType = { forwardedRef: any; }; type stateType = {}; export function logProps(WrappedComponent) { class LogProps extends React.Component<propsType, stateType> { componentDidMount() { console.log("props:", this.props); } render() { return <WrappedComponent {...this.props}/>; } } return React.forwardRef((props: any, ref: any) => { return <LogProps {...props} inputRef={ref}></LogProps>; }); }

      子组件

    import React from "react";
    import { logProps } from "./Test1";
    type propsType = {
      inputRef:any
    };
    type stateType = {};
    interface Test{
      displayName:any
    }
    class Test extends React.Component<propsType, stateType> {
      static displayName: string;//严格模式不声明会报错
      constructor(props) {
        super(props);
        this.state = {};
      }
      render() {
        return (
          <div>
            <label>请输入:</label>
            {/* 使用父组件传递过来的ref声明通过props */}
            <input type="text" ref={this.props.inputRef} />
          </div>
        );
      }
    }
    Test.displayName="child";
    
    //本来需要子组件声明的forwardRef如下写法:
    // return React.forwardRef((props: any, ref: any) => {
    //   return <Test {...props} inputRef={ref}></Test>;
    // });
    //因为使用了高阶函数增强,所以这些东西也放在了高阶函数中使用,这里只是为了说明,父组件调用后ref可以通过HOC组件穿透到子组件使用,
    //这里要注意的是因为props本来是不能传递ref的所以其实ref的名字应该是forwardRef声明的?所以props点出来的ref名字要和forwardRef下面的命名一样。但是父组件的ref的变量名字可以和这里的不一样
    export default logProps(Test);
    

      父组件:

    import React from 'react'
    import Test2 from "./Test2";
    type propsType = {};
    type stateType = {};
    
    interface Test{
      ww:any
    }
    interface Test{
      displayName:any
    }
    class Test extends React.Component<propsType, stateType> {
      static displayName: string;
      constructor(props) {
        super(props);
        this.state = {};
        //父组件创建调用子组件用到的ref
        this.ww=React.createRef();
      }
    
      handleClick=()=>{
        // debugger
        console.log((this.ww as any).current.value)
      }
      render() {
        return <div>
          <Test2 ref={this.ww}></Test2>
          <button onClick={this.handleClick}>点我</button>
        </div>;
      }
    }
    Test.displayName="parent"
    export default Test;
    

      

  • 相关阅读:
    在mvc4中上传、导入和导出excel表方法总结
    ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
    .net下使用NPOI读取Excel表数据
    详解免费高效实用的.NET操作Excel组件NPOI(转)
    Vue 定时执行函数
    decorators.xml的用法
    行内元素和块级元素
    C/C++中printf和C++中cout的输出格式
    IIS 搭建过程
    IIS访问共享文件详解
  • 原文地址:https://www.cnblogs.com/llcdbk/p/13067670.html
Copyright © 2011-2022 走看看