在React中,我们可以通过ref获取DOM和组件。请看下面这个例子:
import React, { PureComponent, createRef } from 'react'
export class App extends PureComponent {
constructor() {
super()
this.state = {
}
this.titleRef = createRef()
this.titleEl = null
}
getNativeDOM() {
// 1.方式一: 在React元素上绑定一个ref字符串
console.log(this.refs.why)
// 2.方式二: 提前创建好ref对象, createRef(), 将创建出来的对象绑定到元素
console.log(this.titleRef.current)
// 3.方式三: 传入一个回调函数, 在对应的元素被渲染之后, 回调函数被执行, 并且将元素传入
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
通过上面例子我们可以看出来,在React中获取DOM元素主要有三种方式:
方式一: 在React元素上绑定一个ref字符串
我们可以直接在this.refs
这个对象上获取到对应的DOM元素。我们只需要在render
函数中,将对应的DOM元素绑定到this.refs
上即可,例如案例中的<h2 ref="why">Hello World</h2>
。
方式二: 提前创建好ref对象, createRef(), 将创建出来的对象绑定到元素
我们可以在constructor
函数中使用createRef()
提前创建好一个ref对象,然后将这个对象绑定到对应的DOM元素上。例如:<h2 ref={this.titleRef}>你好啊,李银河</h2>
。
方式三: 传入一个回调函数, 在对应的元素被渲染之后, 回调函数被执行, 并且将元素传入
我们可以在render
函数中,传入一个回调函数,然后在回调函数中,将元素传入即可。例如:<h2 ref={el => this.titleEl = el}>你好啊, 师姐</h2>
。这里的el
就是对应的DOM元素。
最后我们附上控制台的输出结果:
感谢阅读
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我