(精华2020年5月24日更新) react基础篇 ref的三种方式

import React from 'react'

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

    // { current: null }
  }

  componentDidMount() {
    // console.log(`span1: ${this.refs.ref1.textContent}`)
    // console.log(`span2: ${this.ref2.textContent}`)
    // console.log(`span3: ${this.ref3.current.textContent}`)
    setTimeout(() => {
      this.refs.stringRef.textContent = 'string ref got'
      this.methodRef.textContent = 'method ref got'
      this.objRef.current.textContent = 'obj ref got'
    }, 2000)
  }

  render() {
    return <div>
      <p ref="stringRef">span1</p>//第三种
      <p ref={ele => (this.methodRef = ele)}>span2</p>//第二种
      <p ref={this.objRef}>span3</p>
    </div>
  }
}

强调外部函数获取ref

import React from 'react'

// 函数组件也想拿到dom 通过 ref
const TargetFunction = React.forwardRef((props,ref)=>(
    <input type="text" ref={ref}/>
))
export default class FrodWordRefDemo extends React.Component {
  constructor() {
    super()
    this.ref = React.createRef()
  }

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

  render() {
    return <TargetFunction ref={this.ref}>
    </TargetFunction>
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/106312637
今日推荐