ReactJS - findDOMNode() 方法



在使用 React 時,我們可能會遇到需要訪問元件實際瀏覽器 DOM 節點的場景。出於多種原因,這非常有用,例如直接操作 DOM 和整合需要訪問特定元素的第三方庫。我們可以透過使用 react-dom 包提供的 findDOMNode 方法來實現。

什麼是 findDOMNode?

findDOMNode 是一個 react-dom 庫方法,允許我們定位與 React 類元件物件關聯的瀏覽器 DOM 節點。換句話說,它幫助我們識別 React 元件實際渲染的 HTML 元素。

語法

import { findDOMNode } from 'react-dom';
const dn = findDOMNode(componentInstance);

引數

componentInstance − 它是 React 類元件的例項,domNode 將儲存相應的 DOM 元素。

返回值

findDOMNode 函式返回最接近提供的 componentInstance 的第一個瀏覽器 DOM 節點。但是,有一些因素需要考慮:

  • 如果元件渲染為 null 或 false,findDOMNode 將返回 null。

  • findDOMNode 返回具有元件渲染為字串值的文字 DOM 節點。

此外,如果元件提供具有多個子元素的陣列或 Fragment,findDOMNode 將返回第一個非空子元素。

示例

示例 - 選擇輸入應用

當輸入文字在元件中掛載時,我們可以使用 findDOMNode 函式自動選擇它。以下是我們可以更新應用以包含 findDOMNode 函式的方法:

首先,我們需要建立一個 React 應用,然後建立一個名為 SelectingInput.js 的檔案,在這個檔案中,我們將有一個元件來使用 findDOMNode 函式在輸入欄位掛載後自動選擇其中的文字。

現在,當我們單擊“顯示輸入”按鈕時,App 元件將使用 SelectingInput 元件。SelectingInput 元件內的輸入欄位將在掛載後自動選擇其文字。

SelectingInput.js

import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';

class SelectingInput extends Component {
   componentDidMount() {
      const input = findDOMNode(this.inputRef);
      input.select();
   }   
   render() {
      return (
         <div>
            <input
               defaultValue="Hello"
               ref={(input) => (this.inputRef = input)}
            />
         </div>
      );
   }
}

export default SelectingInput;

App.js

import React, { useState } from 'react';
import SelectingInput from './SelectingInput';

function App() {
   const [show, setShow] = useState(false);
   
   return (
      <>
         <button onClick={() => setShow(true)}>Show the input</button>
         <hr />
         {show && <SelectingInput />}
      </>
   );
}

export default App;

輸出

show the input

此示例演示瞭如何在 React 應用中使用 findDOMNode 函式在元件掛載時與 DOM 互動。

示例 - 渲染字串

在這個例子中,我們將建立一個基本的 React 應用程式,它包含兩個元件:App 和 MyComponent。它是一個擴充套件 React 提供的 Component 類的類元件。render 方法返回一個帶有文字“This is a simple string.”的 <h1> HTML 元素。App 元件是我們的應用程式的主要元件。在 componentDidMount 生命週期方法中,它使用 findDOMNode 函式獲取實際的 DOM 節點。然後將獲得的 DOM 節點記錄到控制檯中。在 App 元件的 render 方法中,MyComponent 的例項在 <div> 內渲染。

import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';

class MyComponent extends Component {
   render() {
      return <h1>This is a simple string</h1>; // Rendering to string
   }
}
class App extends Component {
   componentDidMount() {
      const domNode = findDOMNode(this.myComponentInstance);
      console.log(domNode);
   }   
   render() {
      return (
         <div>
            <MyComponent ref={(component) => (this.myComponentInstance = component)} />
         </div>
      );
   }
}

export default App;

輸出

simple string

執行此應用程式時,它將呈現一個簡單的 <h1> 元素,其中包含文字“This is a simple string.”。然後,App 元件的 componentDidMount 生命週期方法將 MyComponent 的關聯 DOM 節點記錄到控制檯中。

示例 - 計數器應用

這是一個使用 findDOMNode 函式的另一個簡單的 React 應用。我們將有一個 Counter 元件,它是一個維護計數狀態的類元件。它有一個按鈕,點選時可以增加計數。componentDidMount 方法將相關的 DOM 節點記錄到控制檯中。我們的主元件是 App,它在 <div> 內渲染 Counter 元件,並使用 ref 屬性獲取對 Counter 例項的引用。

import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';

class Counter extends Component {
   constructor() {
      super();
      this.state = {
         count: 0,
      };
   }   
   handleIncrement = () => {
      this.setState((prevState) => ({ count: prevState.count + 1 }));
   };   
   componentDidMount() {
      const domNode = findDOMNode(this.counterInstance);
      console.log(domNode);
   }   
   render() {
      return (
         <div>
            <h1>Counter: {this.state.count}</h1>
            <button onClick={this.handleIncrement}>Increment</button>
         </div>
      );
   }
}
class App extends Component {
   render() {
      return (
         <div>
            <Counter ref={(component) => (this.counterInstance = component)} />
         </div>
      );
   }
}

export default App;

輸出

counter 4 increment

因此,當我們點選“遞增”按鈕時,計數會增加。在控制檯中,我們將看到元件掛載時記錄的 Counter 元件的關聯 DOM 節點。

總結

findDOMNode 是一個用於彌合 React 虛擬 DOM 和實際瀏覽器 DOM 之間的差距的有用工具。但是我們應該謹慎使用它,並在可能的情況下尋找其他方法,因為直接在我們的 React 應用程式中訪問 DOM 會導致意外行為。

reactjs_reference_api.htm
廣告