react 中ref 属性的三种写法

编程入门 行业动态 更新时间:2024-10-26 03:36:54

react 中ref 属性的<a href=https://www.elefans.com/category/jswz/34/1770022.html style=三种写法"/>

react 中ref 属性的三种写法

目录

1. 字符串 ref

2.dom节点上使用回调函数ref

3.React.createRef()


1. 字符串 ref

最早的ref用法。(由于效率问题,现在官方不推荐使用这种写法。)

1.dom节点上使用,通过this.refs.xxxx来引用真实的dom节点

 <input ref="input1" type="text"/>

代码示例:

class test extends React.Component{constructor(props) {super(props);}showData = ()=>{const x = this.refsalert(x.value)}render() {return (<div><input ref="input1" type="text"/><button onClick={this.showData}> 点我</button></div>)}
}

2.dom节点上使用回调函数ref

<input ref={(currentNode) => {this.textInput = currentNode;}} type="text" />简写:
<input ref={currentNode => this.textInput = currentNode } type="text" />

其中的currentNode节点是,下图:

代码示例:

class test extends React.Component{constructor(props) {super(props);}showData = ()=>{const {input1} = thisalert(input1.value)}saveInput =(currentNode)=>{this.input1 = currentNode}render() {return (<div><input ref={(currentNode)=>{this.input1 = currentNode}} type="text"/>//简写<input ref={currentNode => this.input1 = currentNode} type="text"/><input ref={this.saveInput} type="text"/><button onClick={this.showData}> 点我</button></div>)}
}

3.React.createRef()

       在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性 将能拿到dom节点或组件的实例


注意:React.createRef调用后可以返回一个容器,该容器可以存储被ref 所标识的节点

但是该容器是转人专用,一次只能存一个

myRef = React.createRef()

 代码示例:

class test extends React.Component{//React.createRef调用后可以返回一个容器,该容器可以存储被ref 所标识的节点myRef = React.createRef()constructor(props) {super(props);}showData = ()=>{alert(this.myRef.current.value)}saveInput =(currentNode)=>{this.input1 = currentNode}render() {return (<div><input ref={this.myRef} type="text"/>{/*<input ref={(currentNode)=>{this.input1 = currentNode}} type="text"/>*/}{/*//简写*/}{/*<input ref={currentNode => this.input1 = currentNode} type="text"/>*/}{/*<input ref={this.saveInput} type="text"/>*/}<button onClick={this.showData}> 点我</button></div>)}
}

 

拓展:如何获取多个input输入框中的值?

第一种:

import React,{ Component } from 'react';
class ReplenishData extends Component{constructor(props){super(props);this.state = {}}showVal(name,e){this.setState({[name]:e.target.value});}render(){console.log(this.state);return(<div><input type="text" onChange= {this.showVal.bind(this,"name1")} /><input type="text" onChange={this.showVal.bind(this,"name2")} /><input type="text" onChange={this.showVal.bind(this,"name3")} /><input type="text" onChange={this.showVal.bind(this,"name4")} /><input type="text" onChange={this.showVal.bind(this,"name5")} /><input type="text" onChange={this.showVal.bind(this,"name6")} /></div>)}
}

更多推荐

react 中ref 属性的三种写法

本文发布于:2023-12-05 18:20:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1664931.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:三种   写法   属性   react   ref

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!