温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

React中的ref属性怎么使用

发布时间:2023-04-24 16:10:06 来源:亿速云 阅读:132 作者:iii 栏目:开发技术

今天小编给大家分享一下React中的ref属性怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

ref 简介

React提供的这个ref属性,表示为对组件真正实例的引用,其实就是ReactDOM.render()返回的组件实例;需要区分一下,ReactDOM.render()渲染组件时返回的是组件实例;而渲染dom元素时,返回是具体的dom节点。

例如,下面代码:

const domCom = <button type="button">button</button>;
const refDom = ReactDOM.render(domCom,container);
//ConfirmPass的组件内容省略
const refCom = ReactDOM.render(<ConfirmPass/>,container);
console.log(refDom);
console.log(refCom);

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>
    )
  }
}

以上就是“React中的ref属性怎么使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI