第七节:createRef细节分析

204 阅读1分钟

createRef细节分析

  • 通过createRef 可以创建出一个 ref对象
  • 通过元素的ref属性可以附加到元素上
  • 一般通过构造器中给this上属性赋值一个ref,方便整个组件使用
  • ref只要传递react元素中,就可以通过current属性访问到真实dom节点

ref 是在componentDidMount 和 componentDidUpdate触发前更新

import React, { Component, createRef } from 'react'

class Test extends Component {
  constructor(props) {
    super(props)
    this.divRef = createRef();

    console.log(this.divRef, 111)
  }

  componentDidMount() {
    console.log(this.divRef, 2222)
  }

  componentDidUpdate() {
    console.log(this.divRef, 3333)
  }
  render() {
    return (
      <div ref={ this.divRef }>
        {this.props.children}
      </div>
    )
  }
}


export default class App extends Component {
  state = {
    test: 'this is text'
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({
        test: 'change text'
      })
    }, 1000)
  }
  render() {
    return (
      <div>
        <Test>{ this.state.test }</Test>
      </div>
    )
  }
}

image.png

ref的使用方式

  1. ref -> html元素 -> current -> 真实dom节点
  2. ref -> class组件 -> current -> 组件的实例
  3. ref -> 函数组件(没有实例) -> createRef?附加不到组件上,使用不了
  4. 函数组件的ref的使用
//=> class 组件
import React, { Component, createRef } from 'react'

class Test extends Component {
  constructor(props) {
    super(props)
    this.divRef = createRef();
  }

  render() {
    return (
      <div ref={ this.divRef }>
        {this.props.children}
      </div>
    )
  }
}

export default class App extends Component {
  constructor(props) {
    super(props)
    this.testRef = createRef()
  }
  state = {
    test: 'this is text'
  }
  componentDidMount() {
    console.log(this.testRef)
  }
  render() {
    return (
      <div>
        <Test ref={ this.testRef }>{ this.state.test }</Test>
      </div>
    )
  }
}

image.png

// => 函数组件内部使用 ref
import React, { Component, useRef, useEffect } from 'react'
function Test () {
  const divRef = useRef(null)

  useEffect(() => {
    console.log(divRef)
  })
  return (
    <div ref={ divRef }>hello, Function Ref</div>
  )
}

export default class App extends Component {
  constructor(props) {
    super(props)
    this.testRef = createRef()
  }
  render() {
    return (
      <div>
        <Test></Test>
      </div>
    )
  }
}

image.png