React.forwardRef
React.forwardRef
forwardRef实际上就是当父组件需要得到子组件元素时,可以利用forwardRef来实现。
该方法接受一个有额外ref参数的react组件函数,不调用该方法,普通的组件函数是不会获得该参数的。
应用场景
ref 的作用是获取实例,可能是 DOM 实例,也可能是 ClassComponent 的实例。
但问题来了:
如果目标组件是一个 FunctionComponent 的话,是没有实例的(PureComponent),此时用 ref 去传递会报错
React.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中。这种技术并不常见,但在以下两种场景中特别有用:
- 转发 refs 到 DOM 组件
- 在高阶组件中转发 refs
实例:
点击搜索按钮时,让文本输入框处于聚焦状态
1、普通用法:
import React, { Component } from 'react'
export default class App extends Component {
mytext=null
render() {
return (
<div>
<button type="button" onClick={()=>{
console.log(this.mytext);
this.mytext.current.focus()
this.mytext.current.value="2222"
}}>获取焦点</button>
<Child callback={(el)=>{
console.log(el);、
//el是临时变量,用全局的去接这个值
this.mytext=el
//console.log(el.current);
}}/>
</div>
)
}
}
class Child extends Component {
mytext = React.createRef();
//组件渲染完了执行
componentDidMount() {
this.props.callback(this.mytext);
}
render() {
return (
<div style={{background:"yellow"}}>
<input defaultValue="1111" ref={this.mytext}></input>
</div>
);
}
}
2、使用forwardRef
import React, { Component,forwardRef } from 'react'
export default class App_forwardRef extends Component {
mytext=React.createRef()
render() {
return (
<div>
<button type="button" onClick={()=>{
console.log(this.mytext);
this.mytext.current.value="2222"
}}>获取焦点</button>
<Child ref={this.mytext}/>
</div>
)
}
}
//这里Child是函数式组件
const Child=forwardRef((props,ref)=>{
return (
<div>
<input defaultValue="11111" ref={ref}></input>
</div>
);
})