ref不仅可以用来获取表单元素,还可以用来获取其他任意DOM元素,甚至可以用来获取React组件实例。但绝大多数场景下,应该避免使用ref,因为它破坏了React中以props为数据传递介质的典型数据流。
- 在DOM元素上使用ref
在DOM元素上使用ref是最常见的使用场景。ref接收一个回调函数作为值,在组件被挂载或卸载时,回调函数会被调用,在组件被挂载时,回调函数会接收当前DOM元素作为参数;在组件被卸载时,回调函数会接受null作为参数。
import React, {Component} from 'react';
export default class Test extends Component{
componentDidMount = () => {
this.textInput.focus();
}
render(){
return(
<div>
<input
type = 'text'
ref = {(input) => {this.textInput = input;} }
/>
</div>
)
}
}
- 在组件上使用ref
React组件也可以定义ref,此时ref的回调函数接收的参数是当前组件的实例,这提供了一种在组件外部操作组件的方式。
import React, {Component} from 'react';
class Test extends Component{
componentDidMount = () => {
this.textInput.focus();
}
blur = () => {
this.textInput.blur();
}
render(){
return(
<div>
<input
type = 'text'
ref = {(input) => {this.textInput = input;} }
/>
</div>
)
}
}
export default class Container extends Component{
handleClick = () => {
this.inputInstance.blur();
}
render(){
return(
<div>
<Test ref = {(input) => {this.inputInstance = input}} />
<button onClick = {this.handleClick}>失去焦点</button>
</div>
)
}
}
注意,只能为类组件定义ref属性,而不能为函数组件定义ref属性。
- 父组件访问子组件的DOM节点
在一些场景下,我们可能需要在父组件中获取子组件的某个DOM元素,例如父组件需要知道这个DOM元素的尺寸或位置信息,这时候直接使用ref是无法实现的,因为ref只能获取子组件的实例对象。不过,可以采用一种间接的方式获取子组件的DOM元素:在子组件的DOM元素上定义ref,ref的值是父组件传递给子组件的一个回调函数,回调函数可以通过一个自定义的属性传递。
function Children(props){
//子组件使用父组件传递的inputRef,为input的ref赋值
return(
<div>
<input ref = {this.props.inputRef}>
</div>
)
}
class Parent extends React.Component{
render(){
//自定义一个属性inputRef,值是一个函数
return(
<Children inputRef={el => this.inputElement = el } />
)
}
}