兩種ref的綁定形式
作用:可以標記組件,更快的找到對應位置。
通過ref就可以給元素作標記 ref="xxx" 這種方式在react官方中不推薦使用了,作為了解即可
官網上推薦了兩種ref綁定形式
1.回調的形式<input ref = {el=>this.textInput=el}/>
舉例:輸入框焦點
class App extends React.Component{
componentDidMount(){
this.textInput.focus()
}
render(){
return(
<div>
<input ref={el=>thisInput=el}/>
</div>
)
}
}
2.createRef
(1)創建一個ref的引用。
(2)需要在組件或者dom元素上通過ref做好標記
(3)注意:使用current屬性才可以獲取到dom組件
類組件:
class App extends React.Component{
constructor(){
super()//繼承的時候,第一行必須要寫super 目的就是用來調用父類的構造函數
this.myRef = React.creatRef();//01.-創建了一個ref的引用
}
componentDidMount(){
//03. 注意:使用current屬性才可以獲取到dom組件
this.myRef.current.focos()
}
render(){
return(
<div>
{/*02需要在組件或者dom元素上通過ref做好標記*/}
<input ref={this.myref}/>
<button onClick={onButtonClick}>Focus the input</button>
</div>
)
}
}
函數式組件的應用
函數式組件我們面臨的一個問題:函數式組件中是不能訪問到this的!那么該如何在函數式組件中獲取dom元素?我們可以通過react 16.8之后推出的react Hooks來去解決此問題。采用 useRef這個hooks來去解決在函數式組件中給元素做標記的問題。
1.通過useRef創建一個ref對象
2.通過ref綁定dom或者組件
3.通過inputEl.current屬性就可以獲取到綁定的input dom元素了
const App = props =>{
//1.通過useRef創建一個ref對象
const inputEl = React.useRef(null)
const onButtonClick = ()=>{
//3.通過inputEl.current屬性就可以獲取到綁定的input dom元素了
inputEl.current.focos()
}
return(
<div>
{/*2.通過ref綁定dom或者組件*/}
<input ref = {inputEl}/>
<button onClick={onButtonClick}>按鈕</button>
</div>
)
}