在React中,解耦了對DOM元素的操做,但有時咱們確實須要對DOM操做,好比設置元素的滾動條,這時ref就知足了咱們的需求react
在低版本的react中,ref能夠是一個string類型的屬性,經過this.refs.[refString]來獲取相應的DOM元素,但在高版本的react中已被棄用函數
在高版本中的ref能夠是React.createRef()建立ref屬性 ,也能夠是回調函數,咱們能夠在構造函數中使用React.createRef()來建立一個ref屬性this
例如: this.testRef = React.createRef(); // 建立ref屬性spa
<div ref={this.testRef} /> //將建立的ref屬性做爲一個元素的refcode
this.testRef.current //獲取元素component
ref
的更新會發生在componentDidMount
或 componentDidUpdate
生命週期鉤子以前,因此咱們能夠在componentDidMount
或 componentDidUpdate中處理業務需求
生命週期
注意:不能在函數式組件上使用 ref
屬性,由於它們沒有實例,但能夠在函數式組件內部使用ref回調函數
雖然不能在函數式組件上直接使用ref,但咱們能夠像組件之間傳遞參數同樣來傳遞refstring
例如: render() {鉤子
const TestRefFunc = (props) => {
return (
<div ref={props.testRef}>
);
}
return (
<TestRefFunc testRef={(el) => this.testRefEle = el} />
);
}
知道了在react中如何獲取DOM元素,那麼就能夠對DOM元素操做,設置元素的滾動條,代碼以下
componentDidMount() { // 進入組件
this.testRefEle.current.scrollTop = this.testRefEle.current.scrollHeight;
}
componentUpdateMount() { // 刷新組件
this.testRefEle.current.scrollTop = this.testRefEle.current.scrollHeight;
}