forwardRef的使用

本文介绍了在React中如何通过回调函数和`React.forwardRef`进行父子组件间的通信,以及`forwardRef`在函数式组件中的使用方法。示例代码详细展示了在父组件中获取子组件输入框的引用并操作其焦点和值的过程。

在这里插入图片描述

一 普通用法:

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>
    );
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值