在典型的React數據流中, props
是父組件和子組件交互的惟一方式,要修改一個子組件,你須要使用新的props來從新渲染它。可是在某些狀況下,你須要在典型的數據流以外強制修改子組件、或獲取組件的屬性值。被修改的子組件多是一個React組件的實例,也多是一個DOM元素。html
Refs
提供了一種容許咱們訪問DOM
節點或在render方法中建立的React元素的方式。數組
經過React.crateRef()建立
Refs
可使用React.createRef()
建立,並經過ref
屬性附加到React元素。在構造組件時,一般將Refs
分配給實例屬性,以即可以在整個組件中調用. ref
做爲原生DOM
的屬性傳入bash
class Index extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.getInput = this.getInput.bind(this);
}
componentDidMount() {
console.log(this.componentRef.current)
}
getInput() {
console.log(this.inputRef.current.value)
}
render() {
return (
<div>
<input ref={this.inputRef}/>
<button onClick={this.getInput}>getValue</button>
</div>
)
}
}
複製代碼
不過此例子並不恰當,在實際運用中能經過狀態申明的方式解決,就避免使用ref
。 ref
做爲組件的屬性傳入函數
class IndexPage extends React.PureComponent{
constructor(props) {
super(props);
this.componentRef = React.createRef()
}
componentDidMount() {
console.log(this.componentRef.current)
}
render() {
return (
<div>
<Ref ref={this.componentRef} />
</div>
);
}
}
複製代碼
當ref
傳遞給render中的元素時,對該節點的引用能夠經過生成的Refs
對象的current屬性訪問。但current屬性的值因節點的類型不一樣而有所不一樣。ui
ref
做用於html元素時,構造函數中使用React.createRef()
建立的ref
接收底層DOM
元素做爲其current屬性的值。ref
做用於class申明的React
組件時,構造函數中使用React.createRef()
建立的ref
接收組件實例做爲其current屬性的值。DOM
元素或組件的實例傳遞給current屬性,在組件卸載時給current屬性值傳入 null
,ref
會在 componentDidMount
或 componentDidUpdate
生命週期鉤子函數觸發前更新。refs
能夠經過回調函數的形式建立,它能助你更精細地控制什麼時候refs被設置和解除。 回調函數接收DOM
元素或React組件實例做爲參數,並將該參數添加到實例屬性上,以使它們能在其餘地方被存儲和訪問。回調函數形式建立的ref
,經過回調函數的參數直接引用不須要經過current。 ref
做爲原生DOM
的屬性傳入this
class Index extends React.Component {
constructor(props) {
super(props);
this.setInputRef = el => {
this.inputRef = el
};
this.getInput = this.getInput.bind(this);
}
getInput() {
console.log(this.inputRef)
}
render() {
return (
<div>
<input ref={this.setInputRef} />
<button onClick={this.getInput}>getValue</button>
</div>
)
}
}
複製代碼
ref
做爲組件的屬性傳入spa
class IndexPage extends React.PureComponent{
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.componentRef)
}
render() {
return (
<div>
<CallBackRef ref={ el => {this.componentRef = el}} />
</div>
);
}
}
複製代碼
當ref
做爲原生DOM
的屬性傳入時回調函數的參數便是該DOM
對象,ref
做爲組件的屬性傳入時,回調函數的參數便是該React組件的實例對象。React將在組件掛載時,會調用ref
回調函數並傳入對象參數。在 componentDidMount 或 componentDidUpdate 觸發前,React 會保證 refs 必定是最新的。code
當組件插入到 DOM 後,ref
屬性添加一個組件的引用於到 this.refs
,經過this.refs.xxx
獲取對節點的引用component
class Index extends React.Component {
constructor(props) {
super(props);
this.getInput = this.getInput.bind(this);
}
getInput() {
console.log(this.refs.inputRef)
}
render() {
return (
<div>
<input ref="inputRef" />
<button onClick={this.getInput}>getValue</button>
</div>
)
}
}
複製代碼
在React16.3以後的版本中該方法已經棄用,建議使用前兩種。cdn