1. 程式人生 > >ref實現輸入框聚焦

ref實現輸入框聚焦

關於ref我們是怎麼理解的呢?
我們可以通過React.createRef()建立一個 ref節點,並將其打印出來。
程式碼如下:

import React,{Component} from 'react'
import './MyRef.less'
class MyRef extends Component{
  constructor(props){
    super(props)
    this.myRef=React.createRef()
    console.log('this.myRef>>>',this.myRef)  }
  render(){
    return(
      <div ref={this.myRef}>
      </div>
    )
  }
}
export default MyRef

檢視控制檯我們可以看到,我們的ref取到的其實就是一個html的dom節點,或者說react元素

如果我們想實現點選按鈕,輸入框聚焦和頁面載入進來輸入框聚焦又應該怎麼做呢?
(一)當我點選按鈕,想要input框聚焦,這個時候的話,就是我們點選的時候要取到這個輸入框節點,並且讓它聚焦

程式碼如下

import React,{Component} from 'react'
import './MyRef.less'
class MyRef extends Component{
  constructor(props){
    super(props)
    this.textInput=React.createRef()
    }
  focusTextInput=()=>{
    this.textInput.current.focus()
  }
  render(){
    return(
      <div>
        <input 
          type="text"
          ref={this.textInput}
        />
        <input
          type="button"
          value="focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    )
  }
}
export default MyRef

(二)那如果我們想要輸入框在頁面載入就聚焦,我們應該怎麼做呢?
React 會在元件載入時將 DOM 元素傳入 current 屬性,在解除安裝時則會改回 null。
ref 的更新會發生在componentDidMount 或 componentDidUpdate 生命週期鉤子之前。
那這個時候就需要用到componentDidMount
textarea中的內容

<textarea 
    rows={4}
    placeholder="請輸入您的評論"
    value={this.state.content}
    onChange={this.handleContentChange}
    className="ant-input"
    ref={(textarea)=>this.textarea=textarea}       
/>     

通過ref直接取到這個textarea的dom物件,然後再進行聚焦

componentDidMount(){
    this.textarea.focus()
  }

by我還差遠了,差的很遠