class MyButton extends React.Component {
render () {
return (
// 5. 当 ref 挂载完成,ref.current 将指向 <button> DOM 节点。
<button ref={this.props.child}>
{this.props.children}
</button>
)
}
}

const FancyButton = React.forwardRef((props, ref) => (
// 3. React 传递 ref 给 fowardRef 内函数 (props, ref) => ...,作为其第二个参数。
// 4. 我们向下转发该 ref 参数,将其指定为 JSX 属性。
<MyButton child={ref} className="FancyButton">
{props.children}
</MyButton>
))

class App extends React.Component {
constructor (props) {
super(props);
// 1. 我们通过调用 React.createRef 创建了一个 React ref 并将其赋值给 ref 变量。
this.parentComponent = React.createRef()
}
componentDidMount () {
console.log(this.parentComponent.current)
}
render () {
return (
<div>
{/* 2. 我们通过指定 ref 为 JSX 属性,将其向下传递 */}
<FancyButton ref={this.parentComponent}>点击</FancyButton>
</div>
)
}
}