一 普通用法:
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);、
this.mytext=el
}}/>
</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>
);
}
}
二 使用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>
)
}
}
const Child=forwardRef((props,ref)=>{
return (
<div>
<input defaultValue="11111" ref={ref}></input>
</div>
);
})