本文共 1168 字,大约阅读时间需要 3 分钟。
react useref
Check out my first, if you’re new to them.
如果您是新手,请先查看我的 。
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: {count} )}ReactDOM.render(, 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 by Flavio Copes () on .
见笔由弗拉维奥·科佩斯( 上) 。
翻译自:
react useref
转载地址:http://cmqgb.baihongyu.com/