3.使用ref的三种方式

(1)字符串的方式

import React, { Component } from 'react'

export default class Father extends Component {

  componentDidMount(){
    console.log(this.refs.refElement);
  }

  render() {
    return (
      <div>
        <input ref={ 'refElement' }></input>
        <button onClick={this.fn}>123</button>
      </div>
    )
  }
}

(2)函数的方式

import React, { Component } from 'react'

export default class Father extends Component {

  componentDidMount(){
    console.log(this.refElement);
  }

  render() {
    return (
      <div>
        <input ref={ ref => this.refElement = ref }></input>
        <button onClick={this.fn}>123</button>
      </div>
    )
  }
}

(3)react.CreateRef的方式

import React, { Component } from 'react'

export default class Father extends Component {

  refElement = React.createRef();

  componentDidMount(){
    console.log(this.refElement.current);
  }

  render() {
    return (
      <div>
        <input ref={this.refElement}></input>
        <button onClick={this.fn}>123</button>
      </div>
    )
  }
}

ref的使用场景

这里我们说一个比较常见的场景,就是点击按钮让输入框聚焦:

通过获取DOM后,调用DOM上的focus方法API,来让input框进行聚焦。

同时ref也可以适用于一些DOM元素的动画效果,例如移动,变大变小,都需要通过ref来控制DOM,进行操作。

import React, { Component } from 'react'

export default class Father extends Component {

  refElement = React.createRef();

  componentDidMount(){
    console.log(this.refElement.current);
  }

  fn = ()=>{
    this.refElement.current.focus();
  }

  render() {
    return (
      <div>
        <input ref={this.refElement}></input>
        <button onClick={this.fn}>聚焦</button>
      </div>
    )
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值