说说对于react refs的理解以及应用场景
refs提供了一种方式,允许我们访问DOM节点或在render方法中创建React元素。创建ref的形式有四种:
-
传入字符串,使用时通过this.refs传入的字符串的格式获取对应的元素,只需要在对应元素或组件中添加ref属性
class MyComponent extends React.Component { constructor(props){ super(props); this.myRef = React.createRef(); } render(){ return <div ref="myref">; } }
-
访问当前节点的方式如下:
this.refs.myref.innerHTML = "hello";
-
传入对象,对象是通过React.createRef()方式创建出来,使用时获取到创建的对象中存在current属性就是对应的元素refs通过React.createRef()创建,然后将ref属性添加到React元素中,如下:
class MyComponent extends React.Component { constructor(props){ super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; } }当ref被传递给render中的元素时,对该节点的引用可以在ref的current属性中访问
const node = this.myRef.current; -
传入函数,该函数会在DOM被挂载时进行回调,这个函数会传入一个元素对象,可以自己保存,使用时,直接拿到之前保存的元素对象即可
当ref传入为一个函数时,在渲染和过程中,回调函数参数会传入一个元素对象,然后通过实例将自己对象进行保存
class MYComponent extends React.Component { constructor(props){ super(props); this.myRef = React.createRef(); } render(){ return <div ref={element => this.myRef = element} />; } }获取ref对象只需要通过先前存储的对象即可
const node = this.myRef传入hook,hook是通过useRef()方式创建,使用时通过生成hook对象的current属性就是对应的元素
通过useRef创建一个ref,整体使用方式与React.createRef一致
function App(props) { const myref = useRef() return ( <> <div ref={myref}></div> </> ) }获取ref属性也是通过hook对象的current属性
const node = myref.current;应用场景
- 对Dom元素焦点控制、内容选择控制、控制
- 对Dom元素内容设置及媒体播放
- 对Dom元素的操作和组件实例的操作(ant design pro中proTable使用ref来进行表格数据的重载)
- 集成第三方Dom库