(1)字符串的方式
import React, { Component } from 'react'
export default class Father extends Component {
componentDidMount(){
console.log(this.refs.refElement);
}
render() {
return (
<div>
<input ref={ 'refElement' }></input>
<button onClick={this.fn}>123</button>
</div>
)
}
}
(2)函数的方式
import React, { Component } from 'react'
export default class Father extends Component {
componentDidMount(){
console.log(this.refElement);
}
render() {
return (
<div>
<input ref={ ref => this.refElement = ref }></input>
<button onClick={this.fn}>123</button>
</div>
)
}
}
(3)react.CreateRef的方式
import React, { Component } from 'react'
export default class Father extends Component {
refElement = React.createRef();
componentDidMount(){
console.log(this.refElement.current);
}
render() {
return (
<div>
<input ref={this.refElement}></input>
<button onClick={this.fn}>123</button>
</div>
)
}
}
ref的使用场景
这里我们说一个比较常见的场景,就是点击按钮让输入框聚焦:
通过获取DOM后,调用DOM上的focus方法API,来让input框进行聚焦。
同时ref也可以适用于一些DOM元素的动画效果,例如移动,变大变小,都需要通过ref来控制DOM,进行操作。
import React, { Component } from 'react'
export default class Father extends Component {
refElement = React.createRef();
componentDidMount(){
console.log(this.refElement.current);
}
fn = ()=>{
this.refElement.current.focus();
}
render() {
return (
<div>
<input ref={this.refElement}></input>
<button onClick={this.fn}>聚焦</button>
</div>
)
}
}