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)} />
}
react获取dom元素