React-Refs转发

本文介绍了React在V16之前和之后关于Refs的使用变化,特别强调了V16之后引入的createRef API,以及如何在高阶组件中转发Refs,确保父组件能够正确引用子组件的DOM元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

V16之前


class Parent extends Component {
    constructor(props, context) {
        super(props, context);
        this.r = null
    }
 	 componentDidMount() {
        this.r.onClick()
    }
    render() {
        return (
            <div>
                <Child ref={r => this.r = r} />
            </div>
        )
    }
}

但是这个方式有个问题,组件渲染时,行内函数会执行两次,第一次为初始值,第二次才是真正的DOM

V16之后

新增了createRef API

1、使用React.createRef()创建Ref

	class Child extends React.Component{
	  constructor(props){
	    super(props);
	    this.myRef=React.createRef();
	    //React16.3中创建Ref的方法
	  }
	  render(){
	    return <input ref={this.myRef}/>
	  }
	}

2、为了能让子组件中的元素接收来自父组件的ref,就要让子组件接收 ref并且通过React.forwardRef转发给元素

import React, {Component} from 'react';

const FancyButton = React.forwardRef((props, ref) => (
    <button ref={ref}>{props.children}</button>
))

class Parent extends Component {
    constructor(props, context) {
        super(props, context);
        this.r = React.createRef()
    }

    render() {
        return (
            <FancyButton ref={this.r}>Click me!</FancyButton>
        );
    }
}

这样父组件的ref this.r就能传递给子组件中的ref了

3、使用父组件的current属性,获取当前元素

this.r.curent

demo地址

在高阶组件转发refs

待定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值