React ref的转发

在前面学习ref时讲过,ref不能应用于函数式组件:
因为函数式组件没有实例,所以不能获取到对应的组件对象
在这里插入图片描述

但是,在开发中我们可能想要获取函数式组件中某个元素的DOM,这个时候我们应该如何操作呢?

  • 方式一:直接传入ref属性(错误的做法)
  • 方式二:通过forwardRef高阶函数;
    在这里插入图片描述
import React, {PureComponent, createRef, forwardRef} from 'react';
class Home extends PureComponent{
    render() {
        return <h2>Home</h2>
    }
}
/*function Profile(props) {
    return <h2>Profile</h2>
}*/
const Profile = forwardRef(function Profile(props, ref) {
    return <h2 ref={ref}>Profile</h2>
})
class App extends PureComponent {
    constructor(props) {
        super(props);
        this.titleRef = createRef()
        this.homeRef = createRef()
        this.profileRef = createRef()
    }
    render() {
        return (
            <div>
                <h2 ref={this.titleRef}>hello</h2>
                <Home ref={this.homeRef} />
                <Profile ref={this.profileRef} />
                <button onClick={e => this.printRef()}>打印ref</button>
            </div>
        );
    }
    printRef () {
        console.log(this.titleRef.current)
        console.log(this.homeRef.current)
        console.log(this.profileRef.current)
    }
}
export default App;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值