瞭解一下Refs
Refs
提供了一種訪問 DOM
節點或在 render
方法中建立的 React
元素的方法。
refs
是 React
元件中非常特殊的 props
,可以附加在任何一個元件上。元件被呼叫時會新建一個該元件的例項,而 refs
就會指向這個例項。
在 react\lib\ReactBaseClasses.js
檔案中,可以看出每個元件都存在 refs
屬性。
/** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } 複製程式碼
在React元件上新增refs
1.使用字串的方式新增 refs
格式: ref='string'
import React, { Component } from 'react'; import './App.css'; import ReactDOM from 'react-dom'; class Children extends Component { render() { return <div> 子元件 </div> } } class App extends Component {s render() { return ( <div className="App"> {/* 使用字串方式 */} <Children ref='children' /> </div> ); } componentDidMount() { console.log(this); console.log('*******************************'); console.log(this.refs.children); } } 複製程式碼
輸出結果:

refs 可以是字串,同樣可以是回撥函式。
2.使用 回撥函式 的方式新增 refs
render
方法修改如下:
render() { return ( <div className="App"> {/* 使用字串方式 */} {/* <Children ref='childern' /> */} {/* 使用回撥函式方式 */} <Children ref={ref=>this.childrenRef=ref} /> </div> ); } 複製程式碼

想要獲取當前 React
元件的例項(引用)可以使用 this
,獲取所擁有子元件的例項(引用)可以使用 refs
。
在 React
元件上新增 refs
,獲取到的是元件的例項。而如果在原生的Dom元件上新增refs獲取到的事什麼呢?接著看
在DOM元素上新增refs
class App extends Component { constructor(props){ super(props); } render() { return ( <div className="App"> <input type='text' ref='input'/> </div> ); } componentDidMount() { console.log(this); console.log('*******************************'); console.log(this.refs.input); } } 複製程式碼
結果如下:

使用回撥函式同理,獲取到的都是DOM節點。
Refs 和函式元件
refs
無法應用於函式元件(無狀態元件),因為函式元件掛載時只是方法呼叫,沒有新建例項。
如果需要引用它,則應該將元件轉換為類,就像您需要生命週期方法或狀態時一樣。
但是,只要引用DOM元素或類元件,就可以在函式元件中使用ref屬性