How to access DOM elements in React?

In React, you can use the ref property to reference DOM elements. Here are some methods for accessing DOM elements:

  1. generate a reference()
  2. reference
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    console.log(this.myRef.current); // 打印DOM元素
  }

  render() {
    return <div ref={this.myRef}>Hello, World!</div>;
  }
}

In the example above, a ref object was created using the createRef() function and assigned to the myRef property. In the componentDidMount() lifecycle method, the corresponding DOM element can be accessed using this.myRef.current.

  1. Obtain DOM elements using a callback function.
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = null;
  }

  componentDidMount() {
    console.log(this.myRef); // 打印DOM元素
  }

  render() {
    return <div ref={ref => (this.myRef = ref)}>Hello, World!</div>;
  }
}

In the example above, by passing a callback function to the ref attribute, you can access the corresponding DOM element within the callback function.

It is important to note that in functional components, you can use useRef() to create a ref object for accessing DOM elements.

bannerAds