Ref 转发是一个可选特性,其允许某些组件接收 ref,并将其向下传递(换句话说,“转发”它)给子组件
注意事项:
- 第二个参数 ref 只在使用 React.forwardRef 定义组件时存在。常规函数和 class 组件不接收 ref 参数,且 props 中也不存在 ref
- Ref 转发不仅限于 DOM 组件,你也可以转发 refs 到 class 组件实例中
- 当你开始在组件库中使用forwardRef时,你应当将其视为一个破坏性更改,不推荐使用。
refs与高级函数HOC一起使用
function refHoc(Component){
class RefHoc extends React.Component{
render(){
const {forwardedRef, ...rest} = this.props;
return <Component forwardedRef={forwardedRef} {...rest}/>
}
}
return React.forwardRef((props, ref)=> {
return <RefHoc {...props} forwardedRef={ref} />;
});
}
class MyInput extends React.Component {
render(){
return <input type="text" ref={this.props.forwardedRef}/>
}
}
const MyInput2 = refHoc(MyInput);
function App(){
const ref = React.createRef();
return(<div>
<button onClick={()=>{ref.current.focus()}}>点击</button>
<MyInput2 ref={ref}/>
</div>)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);