React的ref有3种用法:

1. 字符串(已废弃)
2. 回调函数
3. React.createRef() (React16.3提供)

1. 字符串

最早的ref用法。

1.dom节点上使用,通过this.refs[refName]来引用真实的dom节点

<input ref="inputRef" /> //this.refs['inputRef']来访问

2.类组件上使用,通过this.refs[refName]来引用组件的实例

<CustomInput ref="comRef" /> //this.refs['comRef']来访问

2. 回调函数

回调函数就是在dom节点或组件上挂载函数,函数的入参是dom节点或组件实例,达到的效果与字符串形式是一样的,
都是获取其引用。

回调函数的触发时机:

1. 组件渲染后,即componentDidMount后
2. 组件卸载后,即componentWillMount后,此时,入参为null
3. ref改变后

1.dom节点上使用回调函数

<input ref={(input) => {this.textInput = input;}} type="text" />

2.类组件上使用

<CustomInput ref={(input) => {this.textInput = input;}} />

3.可用通过props跨级传递的方式来获取子孙级dom节点或组件实例

下面是在跨两级获取到孙级别的组件内部的dom节点

function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
function Parent(props) {
return (
<div>
My input: <CustomTextInput inputRef={props.inputRef} />
</div>
);
}
class Grandparent extends React.Component {
render() {
return (
<Parent
inputRef={el => this.inputElement = el}
\/>
);
}
}

3.React.createRef()

在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性
将能拿到dom节点或组件的实例
例如:

class Child extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
}
componentDidMount(){
console.log(this.myRef.current);
}
render(){
return <input ref={this.myRef}/>
}
}

4.React.forwardRef

同样是React 16.3版本后提供的,可以用来创建子组件,以传递ref。
例如:

//子组件(通过forwardRef方法创建)
const Child=React.forwardRef((props,ref)=>(
<input ref={ref} />
)); //父组件
class Father extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
}
componentDidMount(){
console.log(this.myRef.current);
}
render(){
return <Child ref={this.myRef}/>
}
}

子组件通过React.forwardRef来创建,可以将ref传递到内部的节点或组件,进而实现跨层级的引用。

forwardRef在高阶组件中可以获取到原始组件的实例。

例如:

//生成高阶组件
const logProps=logProps(Child); //调用高阶组件
class Father extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
}
componentDidMount(){
console.log(this.myRef.current);
}
render(){
return <LogProps ref={this.myRef}/>
}
} //HOC
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
} render() {
const {forwardedRef, ...rest} = this.props; // Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
} // Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
//生成高阶组件
const logProps=logProps(Child); //调用高阶组件
class Father extends React.Component{
constructor(props){
super(props);
this.myRef=React.createRef();
}
componentDidMount(){
console.log(this.myRef.current);
}
render(){
return <LogProps ref={this.myRef}/>
}
} //HOC
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
} render() {
const {forwardedRef, ...rest} = this.props; // Assign the custom prop "forwardedRef" as a ref
return <Component ref={forwardedRef} {...rest} />;
}
} // Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}

注意:
1. ref在函数式组件上不可使用,函数式组件无实例,但是其内部的dom节点和类组件可以使用
2. 可以通过ReactDOM.findDOMNode(),入参是一个组件或dom节点,返回值的组件对应的dom根节点或dom节点本身
   通过refs获取到组件实例后,可以通过此方法来获取其对应的dom节点
3. React的render函数返回的是vDom(虚拟dom)

参考:https://blog.csdn.net/liangklfang/article/details/72858295
         https://blog.csdn.net/liwusen/article/details/80009968

React ref的用法的更多相关文章

  1. vue里ref ($refs)用法

    ref 有三种用法: 1.ref 加在普通的元素上,用this.ref.name 获取到的是dom元素 2.ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方 ...

  2. 你不可不知的 React Native 混合用法(Android 篇)

    前言 当前 React Native 虽说版本更新比较快,各种组件也提供的很全面了,但是在某些情况下,混合开发的方式才会快速缩短开发周期,原因无非就是原生平台的"底蕴"无疑更深,拥 ...

  3. React Ref 和 React forwardRef

    Ref 和Dom,Ref是reference(引用)的简写. 能力:大多数情况下,props前递可以解决一切问题,但是依然有需要触达React实例或者Dom节点的情况,这时候应该使用React Ref ...

  4. React Ref 其实是这样的

    大家好,我是Mokou,好久没有冒泡了,最近一直在看研究算法和数据结构方面的东西,但是似乎很多前端不喜欢看这种东西,而且目前本人算法方面也很挫,就不献丑了. 当然了,最近也开始研究React了,这篇文 ...

  5. React之ref详细用法

    在react典型的数据流中,props传递是父子组件交互的唯一方式:通过传递一个新的props值来使子组件重新re-render,从而达到父子组件通信.当然,就像react官网所描述的一样,在reac ...

  6. React Native中ref的用法(通过组件的ref属性,来获取真实的组件)

    ref是什么? ref是组件的特殊属性,组件被渲染后,指向组件的一个引用.可以通过组件的ref属性,来获取真实的组件.因为,组件并不是真正的DOM节点,而是存在于内存中的一种数据结构,称为虚拟的DOM ...

  7. React中ref的用法

    在React数据流中,父子组件唯一的通信方式是通过props属性:那么如果有些场景需要获取某一个真实的DOM元素来交互,这时候就要用到React的refs属性. 1.可以给DOM元素添加ref属性 c ...

  8. React Native ref高级用法&&setNativeProps使用

    ref属性不只是string ref属性不仅接受string类型的参数,而且它还接受一个function作为 callback.这一特性让开发者对ref的使用更加灵活. render() { retu ...

  9. C#关于ref的用法(多个实参值的传递)

    按照C#默认的按值调用参数的传递机制,不能刻编写出一个方法来实现两个int类型的值交换,因为一个方法只能对应一个返回值,如何实现将两个交换的值传递回去,这里我将用到的是ref修饰符. 使用ref的单值 ...

随机推荐

  1. Linux命令应用大词典-第19章 文件系统管理

    19.1 mkfs:创建Linux文件系统 19.2 mke2fs:创建ext2.3.4文件系统 19.3 mkfs.ext4:创建ext4文件系统 19.4 mkfs.ext3:创建ext3文件系统 ...

  2. Python常用函数--return 语句

    在Python教程中return 语句是函数中常用的一个语句.return 语句用于从函数中返回,也就是中断函数.我们也可以选择在中断函数时从函数中返回一个值.案例(保存为 function_retu ...

  3. 编写你自己的Python模块

    其实网上Python教程挺多的,编写你自己的模块很简单,这其实就是你一直在做的事情!这是因为每一个 Python 程序同时也是一个模块.你只需要保证它以 .py 为扩展名即可.下面的案例会作出清晰的解 ...

  4. system_Class类说明文档

    system_Class类是FastCMS系统必须的,全局对象system是system_Class的实例,其主要包含二类操作: 1.token 操作: token可以存储当前访客的私有信息,取代se ...

  5. StreamSets小白踩过的一些坑

    由于公司业务上的需求,需要实时监控mysql数据库的数据的增长,并将数据同步到另一个平台,所以就问老大使用什么工具比较好,老大推荐使用StreamSets,还说在测试环境都已经部署好了StreamSe ...

  6. 四:ResourceManger Restart

    概述: RM是yarn中最重要的组件.但是只有一个RM,因此存在单点失败的问题.RM的重启有两种方式: 1.(Non-work-preserving RM restart) 不保留工作状态的重启   ...

  7. 《javascript模式--by Stoyan Stefanov》书摘--汇总

    <javascript模式--by Stoyan Stefanov>书摘--基本技巧 http://www.cnblogs.com/liubei/p/JavascriptModeLog1. ...

  8. JS判断是IOS还是Android以及如何解决h5打包后在ios下内容与状态栏重叠问题

    h5打包后在ios下内容与状态栏重叠问题: 1:知道设备的类型: var u = navigator.userAgent, app = navigator.appVersion; var isAndr ...

  9. 针对“来用”团队项目之NABC分析

    本项目特点之一:扩展性强 NABC分析: N(need):我们这个开发的这个软件主要是集娱乐软件和实用工具于一身的大容器,这里面有很多应用程序,针对不同用户需要,至少有一款应用程序能够满足用户的需要, ...

  10. js 拼接字符串时,本来想要’#1′ ,返回的却是’#01′

    今天在操作一个元素时,id值是拼接的. var index = $(this).attr(‘index’);    //0var id = ‘#’ + (index+1);    //#01$(id) ...