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;

  


免責聲明!

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



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