同学你好,ref转发这一块属于进阶知识了,我们的课程面向的是小白用户,主要内容以基础为准,因此一般不会涉及到很复杂的知识点。对于同学说的这个ref转发,老师结合官方文档介绍,写了一个简单的示例,同学可以作为扩展,参考理解下:
主要涉及到的几个文件目录结构如下:

首先给出一个高阶组件logProps
import React from 'react'
function logProps(WrappedComponent) {
const WrappedComponentName = WrappedComponent.displayName || WrappedComponent.name
class LogProps extends React.Component {
render() {
return <WrappedComponent {...this.props} />;
// const { forwardedRef, ...rest } = this.props;
// // 将自定义的 prop 属性 “forwardedRef” 定义为 ref
// return <WrappedComponent ref={forwardedRef} {...this.props} />;
}
}
return LogProps;
// return React.forwardRef((props, ref) => {
// return <LogProps {...props} forwardedRef={ref} />;
// });
}
export default logProps
然后是FancyButton组件
import React from 'react'
import logProps from './logProps'
class FancyButton extends React.Component {
sayHi() {
alert("Hello React")
}
render() {
return <button onClick={this.props.onClick}>FancyButton:{this.props.title}</button>
}
}
// 我们导出 LogProps,而不是 FancyButton。
// 虽然它也会渲染一个 FancyButton。
export default logProps(FancyButton);
在APP.js文件中创造Ref对象,然后检查Ref的值,这里便会发现文档中提到的的问题:
"refs 将不会透传下去。这是因为 ref 不是 prop 属性。就像 key 一样,其被 React 进行了特殊处理。如果你对 HOC 添加 ref,该 ref 将引用最外层的容器组件,而不是被包裹的组件。"
import React from 'react'
import FancyButton from './FancyButton'
class App extends React.Component {
constructor() {
super()
this.state = {
title: "ABC"
}
this.fancyButtonRef = React.createRef()
}
handleClickFancyButton = () => {
this.setState({
title: 123
})
//注意:此处打印出来的Ref是logProps组件,而不是我们想要的FancyButton组件
console.log("this.fancyButtonRef->", this.fancyButtonRef)
}
render() {
return (
<div className="App">
<FancyButton title={this.state.title}
onClick={this.handleClickFancyButton}
ref={this.fancyButtonRef} />
</div>
);
}
}
export default App
测试结果如下:

于是官方文档修改了高阶组件logProps部分代码,如下:
import React from 'react'
function logProps(WrappedComponent) {
const WrappedComponentName = WrappedComponent.displayName || WrappedComponent.name
class LogProps extends React.Component {
render() {
// return <WrappedComponent {...this.props} />;
const { forwardedRef, ...rest } = this.props;
// 将自定义的 prop 属性 “forwardedRef” 定义为 ref
return <WrappedComponent ref={forwardedRef} {...this.props} />;
}
}
// return LogProps;
// 注意 React.forwardRef 回调的第二个参数 “ref”。
// 我们可以将其作为常规 prop 属性传递给 LogProps,例如 “forwardedRef”
// 然后它就可以被挂载到被 LogProps 包裹的子组件上。
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
export default logProps
经过上述修改后,ref指向的便是被包裹组件,即:fancyButton组件,如下:

祝学习愉快~
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星