1. 普通写法
import React, { Component,createRef } from 'react'
export default class App extends Component {
myinput = null;
render() {
return (
<div>
<button onClick={()=>{
this.myinput.current.focus();
}}>获取焦点</button>
<Child cb={el=>{
this.myinput = el;
}}/>
</div>
)
}
}
class Child extends Component {
myinput = createRef();
componentDidMount(){
this.props.cb(this.myinput);
}
render(){
return (
<div style={{background:'yelllow'}}>
<input defaultValue="1" ref={this.myinput}/>
</div>
)
}
}
2. forwardRef
forwardRef-透传ref到子组件
import React, { Component,createRef, forwardRef } from 'react'
export default class App extends Component {
myinput = createRef();
render() {
return (
<div>
<button onClick={()=>{
this.myinput.current.focus();
}}>获取焦点</button>
<Child ref={this.myinput}/>
</div>
)
}
}
const Child = forwardRef((props,ref)=>{
return (
<div style={{background:'pink'}}>
{/* ref必须指向dom元素,不能是组件 */}
<input defaultValue="1" ref={ref}/>
</div>
)
})