【 React 】三种 ref 的方式以及高阶组件必备 ref 转发

it2023-06-20  74

在React中没有直接的API去操作DOM 结构,所以就要用到 ref 来获取DOM结构,常用的方法有以下三种

1、字符串类型的ref

顾名思义 ref接收的是一个字符串,如果你目前还在使用 this.refs.textInput 这种方式访问 refs ,建议用回调函数或 createRef API 的方式代替。因为会有BUG

<div id="app"></div> <script type="text/babel"> //通过ref=""这种方式来去给dom元素进行标记 //如果你目前还在使用 this.refs.textInput 这种方式访问 refs ,我们建议用回调函数或 createRef API 的方式代替。 //https://react.docschina.org/docs/refs-and-the-dom.html class App extends React.Component{ componentDidMount(){ //相当于Vue中的mounted钩子函数 console.log("componentDidMount...",this) this.refs.textInput.focus() } render(){ console.log("render...") return ( <div> <input ref="textInput"/> </div> ) } } ReactDOM.render(<App/>,document.getElementById("app")) </script>

2、函数式ref

顾名思义,ref接收的是一个函数,函数的参数为设置ref属性的DOM结构

<div id="app"></div> <script type="text/babel"> class App extends React.Component{ componentDidMount(){ //相当于Vue中的mounted钩子函数 this.textInput.focus() } render(){ return ( <div> {/*直接用回调函数的方式进行挂载*/} <input ref={ (el)=>{ this.textInput = el} } /> //讲DOM结构挂载到this的属性上,方便调用 </div> ) } } ReactDOM.render(<App/>,document.getElementById("app")) </script>

3、利用react中封装的方法 createRef()

此方法挂载的DOM结构在 current 属性中,如果是标签就是标签DOM,如果是组件就是组件对象。

<div id="app"></div> <script type="text/babel"> class App extends React.Component{ constructor() { super() //继承的时候,子类的constructor里面第一行代码必须写super关键字,目的调用父类的空构造 //函数来去实例化子类本身。 this.myRef = React.createRef() //1.创建了一个ref的引用,并且可以通过this.myRef属性去进行访问 } componentDidMount(){ //相当于Vue中的mounted钩子函数 //3.注意:使用current属性才可以获取到标记的元素本身 this.myRef.current.focus() } render(){ return ( <div> {/*2.需要在组件或者dom元素上面通过ref进行标记*/} <input ref={this.myRef}/> </div> ) } } ReactDOM.render(<App/>,document.getElementById("app")) </script>
最新回复(0)