React -- ref的用法

通过 ref 可以获取到DOM元素 / 组件的实例对象

1. React.createRef方法(推荐使用)

2. ref=函数

3. ref=字符串(不推荐使用)

4. 注意:函数组件不能使用ref,要使用React.forwardRef()

例子

 


1. React.createRef方法(推荐使用)

        this.inputRef = React.createRef()

        <input ref={ this.username } />

        输出元素的DOM对象:this.username.current

 

2. ref=函数

        <input ref={ input => (this.username = input) } />

        输出元素的DOM对象:this.username

 

3. ref=字符串(不推荐使用)

        <input ref='username' />

        输出元素的DOM对象:this.refs.username

 

4. 注意:函数组件不能使用ref,要使用React.forwardRef()

let TextInput = React.forwardRef((props, ref) => {

    return <input ref={ref} />

})

 


例子:

需求:点击按钮让input文本获取焦点

input文本框以及让文本框获取焦点的方法定义在input组件中

在App组件中引入input组件,按钮定义在App组件中

 

关键API:React.createRef()

创建ref后,就可以通过current属性拿到实例

 

Input.js

// Input.js
import React, { Component } from 'react'
export default class Input extends Component {
  constructor() {
    super()
    this.inputRef = React.createRef()
    this.focusInput = this.focusInput.bind(this)
  }
  focusInput() {
    this.inputRef.current.focus()
  }
  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} />
      </div>
    )
  }
}

App.js 

// App.js
import React, { Component } from 'react'
import Input from './Input'
export default class App extends Component {
  constructor() {
    super()
    this.InputComponentRef = React.createRef()
  }
  render() {
    return (
      <div>
        <Input ref={this.InputComponentRef} />
        <button onClick={() => this.InputComponentRef.current.focusInput()}>
          button
        </button>
      </div>
    )
  }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值