ref的作用
react 中,很少直接的操作dom 元素,如果需要操作 dom 元素的话,那么就需要使用到 ref
常见的应用场景
- 管理焦点,文本选择或媒体播放
- 触发强制动画
- 集成第三方 DOM 库
如何使用
传入字符串
使用时通过 this.refs.传入的字符串格式获取对应的元素
传入一个对象
- 对象是通过 React.createRef() 方式创建出来的
- 使用时获取到创建的对象其中有一个current属性就是对应的元素
传入一个函数
- 该函数会在DOM被挂载时进行回调,这个函数会传入一个元素对象,可以自己保存;
- 使用时,直接拿到之前保存的元素对象
举例
import React, {
PureComponent, createRef } from 'react'
export default class App extends PureComponent {
constructor(props) {
super(props);
this.titleRef = createRef();
this.titleEl = null;
}
render() {
return (
<div>
<h2 ref="title">传入一个字符串</h2>
<h2 ref={
this.titleRef}>传入一个对象</h2>
<h2 ref={
element => this.titleEl = element}>传入一个函数</h2>
<button onClick={
e => this