增强组件:
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;
原文:https://www.cnblogs.com/llcdbk/p/13067670.html