ref在类组件和函数组件中的使用
Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素
React中的ref属性可以帮助我们获取子组件的实例或者Dom对象,进而对子组件进行修改
何时使用
管理焦点、文本选择或者媒体播放 触发强制动画 集成第三方dom库
访问ref ref的值根据节点类型而有所不同
当用于html元素时,接收的是dom元素作为其current值 当用于类组件时,接收组件的挂载实hu例作为其current属性
在函数组件上使用ref属性,需要 forwardRef 与 useImperativeHandle 结合使用
ref获取原生DOM三种方式
- 在React元素上绑定一个ref字符串
- 提前创建好ref对象,createRef(),将创建出来的对象绑定到元素
- 传入一个回调函数,在对应的元素被渲染之后,回调函数被执行,并且将元素传入
import React, { PureComponent, createRef } from 'react'
export class App extends PureComponent {
constructor() {
super()
this.state = {
}
this.titleRef = createRef()
this.titleEl = null
}
getNativeDom() {
//方法1
// console.log(this.refs.why)
//方法2
// console.log(this.titleRef)
// 方法三
console.log(this.titleEl)
}
render() {
return (
<div>
{/* <h2 ref="why">Hello world</h2> */}
<h2 ref={this.titleRef}>你会不会</h2>
<h2 ref={el => { this.titleEl = el }}>你会不会</h2>
<button onClick={e => this.getNativeDom()}> 获取Dom</button>
</div>
)
}
}
export default App
this.titleRef.current的值
this.titleRef的值
ref 获取类组件实例
import React, { PureComponent, createRef } from 'react'
class Helloworld extends PureComponent {
render() {
return <h1>hello world</h1>
}
}
export class App extends PureComponent {
constructor() {
super()
this.state = {
}
this.hwRef = createRef()
}
getNativeDom() {
//方法1
// console.log(this.refs.why)
//方法2
// console.log(this.titleRef)
// 方法三
console.log(this.hwRef.current)
}
render() {
return (
<div>
<Helloworld ref={this.hwRef}></Helloworld>
<button onClick={e => this.getNativeDom()}> 获取组件实例</button>
</div>
)
}
}
export default App
ref 函数式组件
import React, { PureComponent, createRef, forwardRef } from 'react'
const Helloworld = forwardRef(function (props, ref) {
return (
<div>
<h1 ref={ref}>Helloworld</h1>
<p>jhhh</p>
</div>
)
})
export class App extends PureComponent {
constructor() {
super()
this.state = {
}
this.hwRef = createRef()
}
getNativeDom() {
//方法1
// console.log(this.refs.why)
//方法2
// console.log(this.titleRef)
// 方法三
console.log(this.hwRef.current)
}
render() {
return (
<div>
<Helloworld ref={this.hwRef}></Helloworld>
<button onClick={e => this.getNativeDom()}> 获取组件实例</button>
</div>
)
}
}
export default App