react获取dom元素_如何在React中引用DOM元素

react获取dom元素

React is great at abstracting away the DOM from you when building apps.

在构建应用程序时,React擅长从您那里提取DOM。

But what if you want to access the DOM element that a React component represents?

但是,如果您想访问React组件代表的DOM元素怎么办?

Maybe you have to add a library that interacts directly with the DOM like a chart library, maybe you need to call some DOM API, or add focus on an element.

也许您必须像图表库一样添加一个与DOM直接交互的库,也许您需要调用一些DOM API或将重点放在某个元素上。

Whatever the reason is, a good practice is making sure there’s no other way of doing so without accessing the DOM directly.

无论是什么原因,一个好的做法是确保没有其他方法可以直接访问DOM。

In the JSX of your component, you can assign the reference of the DOM element to a component property using this attribute:

在组件的JSX中,可以使用以下属性将DOM元素的引用分配给组件属性:

ref={el => this.someProperty = el}

Put this into context, for example with a button element:

将其置于上下文中,例如,使用button元素:

<button ref={el => (this.button = el)} />

button refers to a property of the component, which can then be used by the component’s lifecycle methods (or other methods) to interact with the DOM:

button指的是组件的属性,然后组件的生命周期方法(或其他方法)可以使用它与DOM进行交互:

class SomeComponent extends Component {
  render() {
    return <button ref={el => (this.button = el)} />
  }
}

In a function component the mechanism is the same, you just avoid using this (since it does not point to the component instance) and use a property instead:

在功能组件中,机制是相同的,只是避免使用this (因为它不指向组件实例),而是使用属性:

function SomeComponent() {
  let button
  return <button ref={el => (button = el)} />
}

翻译自: https://flaviocopes.com/react-ref-element/

react获取dom元素

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值