1.直接使用React.createRef()
class a extends React.Component {
constructor(props) {
super(props)
this.firstRef = React.createRef()
}
render() {
return <div ref={this.firstRef}>get div referened</div>
}
}
此時this.firstRef就是div這個標籤的應用。類組件也可以使用這種方法。但是獲取引用是掛載的實例,而不是dom標籤的引用。但是函數式的組件不可以使用,因爲函數式的組件沒有實例
2.使用ref回調函數的形式
class a extends React.Component {
constructor(props) {
super(props)
this.firstRef = null
this.getFirstRef = element => {
this.firstRef = element
}
}
render() {
return <div ref={this.getFirstRef}>get div referened</div>
}
}
此時this.firstRef就是div標籤的引用。
3.refs在組件之間的傳遞
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}
此時this.inputElement就是input標籤的引用。就是通過props將inputRef傳遞給CustomTextInput,然後CustomTextInput通過ref屬性傳遞給input標籤。其實跟上一個通過函數傳遞大同小異。