以前理所当然的认为,只要ref作为props传进去,就可以直接给某个子组件用了,但是实际上不是这样的
const Test = ({ref}) => { return <div ref={ref}> <p>hahahha</p> </div> } class TestWarper extends React.Component { ref = React.createRef(); render() { return <Test ref={this.ref} /> } } // 上面这种情况下,this.ref永远是{current: null},在Test子组件也发现,传进来的ref是undefined
面对这种情况,React有个方法,可以支持Ref的传递:forwardRef
import React, {forwardRef} from ‘react‘; // 包一层forwardRef const Test = forwardRef((props, ref:any) => { return <div ref={ref}> <p>hahahha</p> </div> }) class TestWarper extends React.Component { ref = React.createRef(); render() { return <Test ref={this.ref} /> } } // 这种情况下,this.ref就会是{current: div}了
原文:https://www.cnblogs.com/amiezhang/p/13174745.html