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;
    

      

  • 相关阅读:
    网站SEO关键词优化技巧
    SEO操作流程及网站优化技巧
    Linux服务器工作常用命令总结
    【转载】Linux常用命令大全(非常全!!!)
    myBatis出现Mapped Statements collection already contains value for
    maven打成war包之后没有class文件
    查询每个类型最新的一条记录
    关于 MySQL 的 boolean 和 tinyint(1) (转)
    Mac下的eclipse按住ctrl点击无法查看类文件
    Mac 10.10下安装MySQL5.6.21提示安装失败
  • 原文地址:https://www.cnblogs.com/llcdbk/p/13067670.html
Copyright © 2011-2022 走看看