组件内的标签通过定义ref属性来标识自己。
做一个小实例,如下图所示:
两个输入框,第一个输入框输入内容,点击后面按钮,弹窗显示输入内容;第二输入框,失去焦点弹窗显示输入内容。
这里我需要获取页面DOM input,进而获取输入框内容,下面我来看看在react怎么怎么做。
示例代码如下:
0801_字符串形式refs
字符串形式refs格式:
// refs 声明
<标签 ref="xxx" />
// refs 使用
this.refs.xxx
this.refs.xxx表示的不是虚拟DO M,而是虚拟DOM转化后的真实DOM。
上述字符串形式refs官网不建议使用,它存在一些问题,比如效率问题等,在后续更新中可能废弃。
react还提供一种回调形式的refs,以上面实例为例,使用回调形式ref,代码如下所示:
0802_回调形式refs
回调形式ref格式:
ref={结点参数 => {this.xxx=结点参数}} // 把传递的参数结点挂载在组件实例上
官网说明:
If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn’t matter in most cases.
如果回调函数以内联函数定义,在更新的时候会被调用2次,第一次传递的结点为null,第二次才传递DOM元素。因为每次render都会创建新的函数实例,react需要清理旧的ref,设置新的ref。如果要使用回调形式ref,需要把ref回调定义在组件实例上。
示例代码如下:
0803_回调refs执行次数问题
AP I格式上目前React官方推荐的方式,通用格式:
Class xxx extends React.Component{xxx = React.createRef()return {<标签 ref={this.xxx} />}
}
还是以最开始实例为例,代码如下:
0801_字符串形式refs
说明:
❓QQ:806797785
⭐️源代码仓库地址:https://gitee.com/gaogzhen/react-study
参考:
[1]尚硅谷React教程(2022加更,B站超火react教程)[CP/OL].2020-12-15.p27-p31.