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标签。其实跟上一个通过函数传递大同小异。