使用ref的注意点

获取类组件

import React from 'react'

class Home extends React.Component {
  render() {
    return (
      <div>我是类组件</div>
    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return (
      <div>
        <Home ref={this.myRef} />
        <button onClick={() => this.btnClick()}>按钮</button>
      </div>
    )
  }
  btnClick() {
    console.log(this.myRef.current); // 获取的是类组件的实例对象
  }
}

export default App;
  • 使用  ref 获取的是类组件的实例

ref转发

import React from 'react'

const Home = React.forwardRef(function (props, myRef) {
  return (
    <div ref={myRef}>我是函数式组件</div>
  )
})
class App extends React.Component { constructor(props) { super(props);
this.myRef = React.createRef(); } render() { return ( <div> <Home ref={this.myRef} /> <button onClick={() => this.btnClick()}>按钮</button> </div> ) } btnClick() { console.log(this.myRef.current); } } export default App;
  • 通过 ref 无法直接获取到函数式组件,但可以获取到函数式组件内部的某个DOM
  • 通过  React.createRef 函数创建一个对象,将该对象赋值给函数式组件的  ref 属性
  • 函数式组件需要传递给  React.forwardRef 函数,函数式组件的第二个参数是外界使用时传递进来的  ref 
  • 我们无法直接拿到函数式组件本身,但可以拿到函数式组件当中的某一个元素
posted @ 2021-12-07 00:04  霸哥yyds  阅读(117)  评论(0)    收藏  举报