ref
reference表示引用。
使用场景:直接使用dom元素的某个方法,或者直接使用自定义组件中的某个方法。
- 作用于内置的html组件,得到的是真实的dom
- ref作用于类组件,得到的是类的实例
- ref不能作用于函数组件
ref不再推荐使用字符串赋值,字符串赋值的方式可能会被移除。目前ref推荐使用对象或者函数。
ref是字符串(不推荐):
export default class App extends Component {
handleClick = ()=>{
this.refs.txt.focus()
}
render() {
return (
<div>
<input ref='txt' type="text"/>
<button onClick={this.handleClick}>focus</button>
</div>
)
}
}
ref是对象:
export default class App extends Component {
constructor(props){
super(props)
this.txt = React.createRef()
}
handleClick = ()=>{
this.txt.current.focus()
}
render() {
return (
<div>
<input ref={this.txt} type="text"/>
<button onClick={this.handleClick}>focus</button>
</div>
)
}
}
ref是函数:
export default class App extends Component {
handleClick = () => {
this.txt.focus();
};
render() {
return (
<div>
<input
ref={(el) => {this.txt = el;}}
type='text'
/>
<button onClick={this.handleClick}>focus</button>
</div>
);
}
}
函数的调用时间:
- componentDidMount的时候回调用该函数,此事件中可以使用ref
- 函数的调用在componentDidMount之前
- 如果ref的值发生了变动,分别调用旧的函数以及新函数,旧函数调用的时候传递null,新的函数被调用的时候传递对象
ref 转发
import React, { Component } from 'react'
function A(props, ref){
console.log(props, ref)
return <h1 ref={ref}>A组件</h1>
}
// 传递函数组件,得到一个新的组件,不能传递类组件,并且函数组件必须使用第二个
const NewA = React.forwardRef(A)
export default class App extends Component {
ARef = React.createRef()
componentDidMount() {
console.log(this.ARef) // {current: h1}
}
render() {
return (
<div>
<NewA ref={this.ARef} words="sdfsd"/>
</div>
)
}
}