三种写法"/>
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 属性的三种写法
发布评论