關於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我還差遠了,差的很遠