在这里插入图片描述

一 普通用法:

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>
    );
  }
}

二 使用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>
    );
})
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐