react useref_如何使用useRef React钩子

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

翻译自: https://flaviocopes.com/react-hook-useref/

react useref

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值