function UserName(props,ref) {
return <input ref={ref}></input>
}
const ForwordUsername = React.forwardRef(UserName)
class Form extends React.Component{
constructor(){
super()
this.username = React.createRef() //this.username 就是ForwordUsername组件的实例 this.username.current = new ForwordUsername()
}
getFocus = () => {
this.username.current.focus() //this.username.current.inputRef.current 获取到组件对应的真实dom节点 就是 input框
}
render(){
return (
<form>
<ForwordUsername ref={this.username}/>
<button type="button" onClick={this.getFocus}>让用户名获得焦点</button>
</form>
)
}
}
function UserName(props,ref) {
return <input ref={ref}></input>
}
function forwardRef (functionComponent) {
return class extends React.Component {
render() {
return functionComponent(this.props,this.props.ref2)
}
}
}
const ForwordUsername = forwardRef(UserName) //React.forwardRef返回一个类组件,将这个类组件传给
class Form extends React.Component{
constructor(){
super()
this.username = React.createRef() //this.username 就是UserName组件的实例 this.username.current = new UserName()
}
getFocus = () => {
this.username.current.focus() //this.username.current.inputRef.current 获取到组件对应的真实dom节点 就是 input框
}
render(){
return (
<form>
<ForwordUsername ref2={this.username}/>
<button type="button" onClick={this.getFocus}>让用户名获得焦点</button>
</form>
)
}
}
function UserName(props) {
return <input ref={props.ref2}></input>
}
//函数组件没有this,可以通过
function forwardRef (functionComponent) {
return props => functionComponent(props,props.ref2)
}
const ForwordUsername = forwardRef(UserName) //React.forwardRef返回一个类组件,将这个类组件传给
class Form extends React.Component{
constructor(){
super()
this.username = React.createRef() //this.username 就是UserName组件的实例 this.username.current = new UserName()
}
getFocus = () => {
this.username.current.focus() //this.username.current.inputRef.current 获取到组件对应的真实dom节点 就是 input框
}
render(){
return (
<form>
<ForwordUsername ref2={this.username}/>
<button type="button" onClick={this.getFocus}>让用户名获得焦点</button>
</form>
)
}
}
ReactDOM.render(<Form></Form>,document.getElementById('root'))