react之ref的3种方式

import React from 'react'

export default class RefDemo extends React.Component {
  constructor() {
    super()
    this.objRef = React.createRef()

    // { current: null }
  }

  componentDidMount() {

    setTimeout(() => {
      this.refs.stringRef.textContent = 'string ref got'//字符串
      this.methodRef.textContent = 'method ref got'//回调函数
      this.objRef.current.textContent = 'obj ref got'//React.createRef()

      console.log(this.objRef.current)//

obj ref got

console.log(this.methodRef)//

method ref got

}, 1000) } render() { return ( <>

span1

(this.methodRef = ele)}>span3

span3

) } }

关于forwardRef:


想要将ref传值给子组件,但是props没有ref(源码之ReactElement有提),所以需要通过React.forwardRef传递ref,

import React from 'react'

const TargetComponent = React.forwardRef((props, ref) => (
  
))

export default class Comp extends React.Component {
  constructor() {
    super()
    this.ref = React.createRef()
  }

  componentDidMount() {
    this.ref.current.value = 'ref get input'
  }

  render() {
    return 
  }
}

 

你可能感兴趣的:(react)