React之ref
ref 简介
React提供的这个ref属性,表示为对组件真正实例的引用,其实就是ReactDOM.render()返回的组件实例;需要区分一下,ReactDOM.render()渲染组件时返回的是组件实例;而渲染dom元素时,返回是具体的dom节点。
字符串引用
ref可以设置为字符串值,这种方式基本不推荐使用,或者在未来的react版本中不会再支持该方式,但是可以了解一下。
<input ref="inputRef" />
然后在其他地方如事件回调中通过this.refs.input可以访问到该组件实例,其实就是dom元素节点。
let inputEl = this.refs.input;
//然后通过inputEl来完成后续的逻辑,如focus、获取其值等等
回调函数引用
React 支持给任意组件添加特殊属性。ref 属性接受一个回调函数,它在组件被加载或卸载时会立即执行。
- 当给 HTML 元素添加
ref
属性时,ref
回调接收了底层的 DOM 元素作为参数。 - 当给组件添加
ref
属性时,ref
回调接收当前组件实例作为参数。 - 当组件卸载的时候,会传入
null
ref
回调会在componentDidMount
或componentDidUpdate
这些生命周期回调之前执行。
HTML 元素添加 ref 属性时
import React, { Component } from 'react'
export default class App extends Component {
refcb(instance) {
console.log(instance);
}
render() {
return (
<div>
<input ref={this.refcb} />
</div>
)
}
}
//控制台打印当前dom元素input的实例
import React, { Component } from 'react'
export default class App extends Component {
showInputDom = () =>{
const {userNameInput} = this
console.log(userNameInput);
}
render() {
return (
<div>
<input ref={(c)=>{this.userNameInput = c}} />
<button onClick={() => { this.showInputDom() }}>Click</button>
</div>
)
}
}
//控制台打印当前dom元素input的实例
组件添加 ref 属性
import React, { Component } from 'react'
import Son from "./Son"
export default class App extends Component {
state = { visible: true }
changeVisible() {
this.setState({ visible: !this.state.visible });
}
refcb(instance) {
console.log(instance);
}
render() {
return (
<div>
<button onClick={() => { this.changeVisible() }}>{!this.state.visible ? "挂载" : "卸载" }</button>
{
this.state.visible ? <Son ref={this.refcb}></Son> : null
}
</div>
)
}
}
上述代码,渲染到页面时可以发现console.log
打印出对应的组件实例。点击按钮时,<Son/>
组件也在挂载与卸载之间切换,所以能看到null
和组件实例
的结果。
React.createRef()
在React 16.3版本后,使用此方法来创建ref。将其赋值给一个变量,通过ref挂载在dom节点或组件上,该ref的current属性将能拿到dom节点或组件的实例
import React, { Component } from 'react'
export default class App extends Component {
myref =React.createRef()
handleClick = () => {
console.log(this.myref.current);
}
render() {
return (
<div>
<input ref={this.myref} />
<button onClick={() => { this.handleClick() }}>Click</button>
</div>
)
}
}
上述代码点击Click按钮打印出对应dom元素input
的实例