react useref
Check out my React hooks introduction first, if you’re new to them.
如果您是新手,请先查看我的React hooks简介 。
One React hook I sometimes use is useRef
.
我有时使用的一个React挂钩是useRef
。
import React, { useRef } from 'react'
This hook allows us to access a DOM element imperatively.
这个钩子允许我们强制性地访问DOM元素。
Here’s an example, where I log to the console the value of the DOM reference of the span element that contains the count value:
这是一个示例,其中我将包含计数值的span元素的DOM引用的值登录到控制台:
import React, { useState, useRef } from 'react'
const Counter = () => {
const [count, setCount] = useState(0)
const counterEl = useRef(null)
const increment = () => {
setCount(count + 1)
console.log(counterEl)
}
return (
<>
Count: <span ref={counterEl}>{count}</span>
<button onClick={increment}>+</button>
</>
)
}
ReactDOM.render(<Counter />, document.getElementById('app'))
Notice the const counterEl = useRef(null)
line, and the <span ref={counterEl}>{count}</span>
. This is what sets the link.
注意const counterEl = useRef(null)
行,以及<span ref={counterEl}>{count}</span>
。 这就是设置链接的原因。
Now we can access the DOM reference by accessing counterEl.current
.
现在,我们可以通过访问counterEl.current
来访问DOM引用。
See it on Codepen:
在Codepen上查看:
See the Pen React useRef hook by Flavio Copes (@flaviocopes) on CodePen.
见笔阵营useRef钩由弗拉维奥·科佩斯( @flaviocopes上) CodePen 。
react useref