react中ref的使用

ref

reference表示引用。
使用场景:直接使用dom元素的某个方法,或者直接使用自定义组件中的某个方法。

  1. 作用于内置的html组件,得到的是真实的dom
  2. ref作用于类组件,得到的是类的实例
  3. ref不能作用于函数组件

ref不再推荐使用字符串赋值,字符串赋值的方式可能会被移除。目前ref推荐使用对象或者函数。

ref是字符串(不推荐):

export default class App extends Component {
  handleClick = ()=>{
    this.refs.txt.focus()
  }
  render() {
    return (
      <div>
        <input ref='txt' type="text"/>
        <button onClick={this.handleClick}>focus</button>
      </div>
    )
  }
}

ref是对象:

export default class App extends Component {
  constructor(props){
    super(props)
    this.txt = React.createRef()
  }

  handleClick = ()=>{
    this.txt.current.focus()
  }
  render() {
    return (
      <div>
        <input ref={this.txt} type="text"/>
        <button onClick={this.handleClick}>focus</button>
      </div>
    )
  }
}

ref是函数:

export default class App extends Component {
  handleClick = () => {
    this.txt.focus();
  };
  render() {
    return (
      <div>
        <input
          ref={(el) => {this.txt = el;}}
          type='text'
        />
        <button onClick={this.handleClick}>focus</button>
      </div>
    );
  }
}

函数的调用时间:

  1. componentDidMount的时候回调用该函数,此事件中可以使用ref
  2. 函数的调用在componentDidMount之前
  3. 如果ref的值发生了变动,分别调用旧的函数以及新函数,旧函数调用的时候传递null,新的函数被调用的时候传递对象

ref 转发

import React, { Component } from 'react'

function A(props, ref){
  console.log(props, ref)
  return <h1 ref={ref}>A组件</h1>
}

// 传递函数组件,得到一个新的组件,不能传递类组件,并且函数组件必须使用第二个
const NewA = React.forwardRef(A)
export default class App extends Component {
  ARef = React.createRef()
  
  componentDidMount() {
    console.log(this.ARef) // {current: h1}
  }
  
  render() {
    return (
      <div>
        <NewA ref={this.ARef} words="sdfsd"/>
      </div>
    )
  }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值