ref
基本作用
Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
何时使用
- 管理焦点、文本选择或者媒体播放
- 触发强制动画
- 集成第三方dom库
访问ref
ref的值根据节点类型而有所不同
- 当用于html元素时,接收的是dom元素作为其current值
- 当用于类组件时,接收组件的挂载实hu例作为其current属性
- 在函数组件上使用ref属性,需要 forwardRef 与 useImperativeHandle 结合使用
触发时期
react会在组件挂载时给current属性传入Dom元素,并在组件卸载时传入null值,ref会在componentDidMount和componentDidUpdate生命周期钩子触发前更新
基础用法
- 回调用法
<input type="text" ref={(ref)=>{this.inputRef = ref}}>
- createRef方式
inputRef = createRef()
<input type="text" ref={this.inputRef}}>
进阶用法,绑定在组件上
- 类组件
class App extends Component{
buttonClick(){
this.inputRef.focus()
}
render(){
return(
<div>
<Foo ref = {this.inputRef}>
<button onClick={this.buttonClick}>
</div>
)
}
}
class Foo extends Component {
inputRef = createRef()
focus=()=>{
this.inputRef.current.focus()
}
render(){
return <input type="text" ref={this.inputRef}}>
}
}
- 函数组件(ref转发:fowardRef+ imperativeHandle)
class App extends Component{
buttonClick(){
this.inputRef.current.focus()
}
render(){
return(
<div>
<Foo ref = {this.inputRef}>
<button onClick={this.buttonClick}>
</div>
)
}
}
const Foo =forwardRef((props,ref)=> {
const inputRef =useRef()
useImperativeHandle(ref,()=>{
return {
focus:function(){
inputRef.current.focus()
}
}
})
render(){
return <input type="text" ref={inputRef}}>
}
})
相关概念
- refs 转发:forwardRef refs转发是一项将ref自动的通过组件传递到其一子组件的方法
- useImperativeHandle
useImperativeHandle(ref, createHandle, [deps])
useImperativeHandle可以让你在使用ref时自定义暴漏给父组件的实例值。通常与forwardRef配合使用