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="点击按钮提示数据"/> <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="点击按钮提示数据"/> <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="点击按钮提示数据"/> <button onClick={ this.showData }>点我提示输入框值</button> </div> ) } }
总结:
综合以上三种形式各有优缺点,方式1与方式2写起来比较方便但是比较繁琐,方式三通过传入一个回调函数,不但简化了操作还不失优雅,显得代码逼格高些,但在最新版及以后的版本中,React官方使用函数式编程,所以更推荐使用 create 形式的ref。
原文地址:https://blog.csdn.net/bigpatten/article/details/126848551
查看更多关于React中的ref属性的使用示例详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did222219