關於 React 小書:ref 屬性以及 DOM 操作


Posted by YongChenSu on 2020-12-09

ref 屬性以及 DOM

  1. React 提供 ref 屬性幫我們拿到 DOM 元素節點,但若能不用 ref 則不用。因 React.js 本來就可以做到頁面跟新以及事件監聽。
  2. 當 input 在頁面上 mount 完後,會調用 ref 並將 mount 完成以後的 DOM 節點傳給 ref,這樣即可透過 this.input 取得 DOM 元素。
  3. 在 ComponentDidMount 中使用 DOM 元素並調用 this.input.focus() 的 DOM API,完成頁面加載完成便自動 focus 到輸入框的功能。
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import './index.css'

class AutoFocusInput extends Component {
  componentDidMount() {
    this.input.focus()
  }
  render() {
    return (
      <input ref={(input) => this.input = input} />
    )
  }
}

ReactDOM.render(
  <AutoFocusInput />,
  document.getElementById('root')
)


也可在組件標籤上加上 ref

<Clock ref={(clock) => this.clock = clock} />

但也不建議這麼做。

參考資源


#程式導師實驗計畫第四期 #React #react 小書 #ref







Related Posts

npm ERR! enoent ENOENT: no such file or directory, open ... package.json

npm ERR! enoent ENOENT: no such file or directory, open ... package.json

[BE201] 後端中階:部署:Nginx + PM2

[BE201] 後端中階:部署:Nginx + PM2

七天打造自己的 Google Map 應用入門 - Day00

七天打造自己的 Google Map 應用入門 - Day00


Comments