React中的ref属性的使用

本文介绍了React中字符串形式、create形式和回调函数形式ref的使用,分析了各自的优缺点,并强调了在最新版本中推荐使用createRef的函数式编程风格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 字符串形式的ref

import React, { Component } from 'react'

export default class index extends Component {
  showData = () => {
    // 获取input节点
    const { inputRef } = this.refs

    // 输出input值
    console.log(inputRef.value);
  }
  render() {
    return (
      <div>
        <input ref="inputRef" type="text" placeholder="点击按钮提示数据"/>&nbsp;
        <button onClick={ this.showData }>点我提示输入框值</button>
      </div>
    )
  }
}

2. create形式的ref

import React, { Component } from 'react'

export default class index extends Component {
// React.createRef调用后返回一个容器,存储被ref标识的节点,单一使用。也就是说,没定义一个ref就要调用一次React.createRef
  inputRef = React.createRef()

  showData = () => {
    const refVal = this.inputRef.current

    console.log(refVal.value);
  }
  render() {
    return (
      <div>
        <input ref={ this.inputRef } type="text" placeholder="点击按钮提示数据"/>&nbsp;
        <button onClick={ this.showData }>点我提示输入框值</button>
      </div>
    )
  }
}

3. 回调函数形式的ref

import React, { Component } from 'react'

export default class index extends Component {
  showData = () => {
    const { inputRef } = this

    console.log(inputRef.value);
  }
  render() {
    return (
      <div>
        {/* 这里传入一个回调函数 */}
        <input ref={ currentNode => this.inputRef = currentNode } type="text" placeholder="点击按钮提示数据"/>&nbsp;
        <button onClick={ this.showData }>点我提示输入框值</button>
      </div>
    )
  }
}

总结:

  • 综合以上三种形式各有优缺点,方式1与方式2写起来比较方便但是比较繁琐,方式三通过传入一个回调函数,不但简化了操作还不失优雅,显得代码逼格高些,但在最新版及以后的版本中,React官方使用函数式编程,所以更推荐使用create形式的ref。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值