两种ref的绑定形式

两种ref的绑定形式

作用:可以标记组件,更快的找到对应位置。

通过ref就可以给元素作标记 ref="xxx" 这种方式在react官方中不推荐使用了,作为了解即可

官网上推荐了两种ref绑定形式

1.回调的形式<input ref = {el=>this.textInput=el}/>

举例:输入框焦点

class App extends React.Component{
	componentDidMount(){
		this.textInput.focus()
	}
	render(){
        return(
			<div>
				<input ref={el=>thisInput=el}/>
			</div>
        )
	}
}

2.createRef

​ (1)创建一个ref的引用。

​ (2)需要在组件或者dom元素上通过ref做好标记

​ (3)注意:使用current属性才可以获取到dom组件

类组件:

class App extends React.Component{
	constructor(){
		super()//继承的时候,第一行必须要写super  目的就是用来调用父类的构造函数
		this.myRef = React.creatRef();//01.-创建了一个ref的引用
	}
	componentDidMount(){
		//03. 注意:使用current属性才可以获取到dom组件
		this.myRef.current.focos()
	}
	
	render(){
		return(
			<div>
				{/*02需要在组件或者dom元素上通过ref做好标记*/}
				<input ref={this.myref}/>
				<button onClick={onButtonClick}>Focus the input</button>
			</div>
		)
	}
}

函数式组件的应用

函数式组件我们面临的一个问题:函数式组件中是不能访问到this的!那么该如何在函数式组件中获取dom元素?我们可以通过react 16.8之后推出的react Hooks来去解决此问题。采用 useRef这个hooks来去解决在函数式组件中给元素做标记的问题。

1.通过useRef创建一个ref对象

2.通过ref绑定dom或者组件

3.通过inputEl.current属性就可以获取到绑定的input dom元素了

const App = props =>{
	//1.通过useRef创建一个ref对象
	const inputEl = React.useRef(null)
	const onButtonClick = ()=>{
		//3.通过inputEl.current属性就可以获取到绑定的input  dom元素了
		inputEl.current.focos()
	}
	return(
		<div>
			{/*2.通过ref绑定dom或者组件*/}
			<input ref = {inputEl}/>
			<button onClick={onButtonClick}>按钮</button>
		</div>
	)
}
原文地址:https://www.cnblogs.com/axingya/p/13598832.html