react ref获取dom节点

在React中,可以使用ref来获取DOM节点的引用。以下是一些示例代码,说明如何使用ref来获取DOM节点:

使用React.createRef()(React 16.3版本以及更高版本的推荐方法):

import React, { Component } from 'react';

class MyComponent extends Component {

  constructor(props) {

    super(props);

    // 创建一个ref

    this.myRef = React.createRef();

  }

  componentDidMount() {

    // 在组件挂载后,通过ref获取DOM节点并操作它

    this.myRef.current.focus(); // 例如,聚焦输入框

  }

  render() {

    return <input ref={this.myRef} />;

  }

}

使用回调函数(React 16.3版本之前的方式,不推荐但仍然有效):

import React, { Component } from 'react';

class MyComponent extends Component {

  constructor(props) {

    super(props);

    // 初始化一个ref为null

    this.myRef = null;

  }

  componentDidMount() {

    // 在组件挂载后,通过ref获取DOM节点并操作它

    if (this.myRef) {

      this.myRef.focus(); // 例如,聚焦输入框

    }

  }

  render() {

    return <input ref={(ref) => (this.myRef = ref)} />;

  }

}

无论选择哪种方式,都可以使用ref来获取DOM节点并执行需要的操作。值得注意的是,使用React.createRef()是React官方推荐的方式,因为它在性能和可读性方面更好。

猜你喜欢

转载自blog.csdn.net/sun13047140038/article/details/133362678