react: 三大属性之refs

1. 简介

  • 组件可以通过添加ref属性来表示自己
  • react会收集实例的ref信息,以ref定义的名称为key,定义ref的节点为value,然后将这个key-value放到实例的refs属性中
  • 可以通过this.refs.refName获取该ref对应的节点
  • 不要过度使用ref

2. 字符串形式的ref

字符串形式的ref存在效率问题,可能在未来的版本中移除,不建议使用

//创建组件
class Demo extends React.Component{
	//展示左侧输入框的数据
	showData = ()=>{
		const {input1} = this.refs
                // 弹出input1对应的input输入框中的值
		alert(input1.value)
	}
	render(){
		return(
			<div>
				<input ref="input1" type="text" placeholder="点击按钮提示数据"/>&nbsp;
				<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
			</div>
		)
	}
}
//渲染组件到页面
ReactDOM.render(<Demo/>,document.getElementById('test'))

3. 回调函数形式的ref

  • 回调函数的参数为当前ref所处的节点本身
  • 初始化时调用一次,后面更新时都会重新调用
  • 如果 ref 回调函数是以内联函数(类似下面示例中的ref回调函数)的方式定义的,在更新过程中它会被执行两次,第一次传入参数null,然后第二次会传入参数DOM元素
  • 通过将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的
class Demo extends React.Component{
	//展示左侧输入框的数据
	showData = ()=>{
		const {inputNpde} = this
		alert(inputNpde.value)
	}

	render(){
		return(
			<div>
				<input ref={(currentElement) => this.inputNpde = currentElement } type="text" placeholder="点击按钮提示数据"/>&nbsp;
				<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
			</div>
		)
	}
}
//渲染组件到页面
ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))

4. createRef

  • React.createRef调用后可以返回一个容器,该容器可以存储被ref所标识的节点,该容器是“专人专用”的
  • react解析到节点的ref的值为React.createRef()创建的容器时,react将该节点存储到对应的容器中
  • 通过refName.current获取对应的节点
class Demo extends React.Component{
			myRef = React.createRef()
			//展示左侧输入框的数据
			showData = ()=>{
				alert(this.myRef.current.value);
			}	
			render(){
				return(
					<div>
						<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>&nbsp;
						<button onClick={this.showData}>点我提示左侧的数据</button>&nbsp;
					</div>
				)
			}
		}
		//渲染组件到页面
		ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))
如果文章对您有所帮助,可以点一下推荐哦
原文地址:https://www.cnblogs.com/virgosnail/p/15631086.html