// 函数组件使用forwardRef传递ref const ForwardRefComponent = React.forwardRef((props, ref) => <div ref={ref.bind(this)} {...props}>子组件DOM</div>) export default function TestRef() { let myRef = null; return ( <> <button onClick={() => { console.info(myRef); }}>按钮</button> <ForwardRefComponent ref={(r) => (myRef = r)} /> </> ) } // Class组件使用forwardRef传递ref class Child extends React.Component { constructor(props) { super(props); } render() { return ( <div ref={this.props.forwardedRef}>这是子组件DOM</div> ) } } const wrapper = function (InnerComponent) { return React.forwardRef((props, ref) => { return ( <InnerComponent forwardedRef={ref} {...props} /> ) }) } const W = wrapper(Child) class Parent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return ( <div> <button onClick={() => { console.info(this.myRef.current); }}>按钮</button> <W ref={this.myRef} { ...this.props}/> </div > ) } }