React-组件间通信之onRef方法(refs转发)

React-组件间通信之onRef方法

 

组件间通信除了props外还有onRef方法,不过React官方文档建议不要过度依赖ref。本文使用onRef语境为在表单录入时提取公共组件,在提交时分别获取表单信息。

下面demo中点击父组件按钮可以获取子组件全部信息,包括状态和方法,可以看下demo中控制台打印。

// 父组件
class Parent extends React.Component {
  testRef=(ref)=>{
    this.child = ref
    console.log(ref) // -> 获取整个Child元素
  }
  handleClick=()=>{
    alert(this.child.state.info) // -> 通过this.child可以拿到child所有状态和方法
  }
  render() {
    return <div>
      <Child onRef={this.testRef} />
      <button onClick={this.handleClick}>父组件按钮</button>
    </div>
  }
}
// 子组件
class Child extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      info:'快点击子组件按钮哈哈哈'
    }
  }
  componentDidMount(){
    this.props.onRef(this)
    console.log(this) // ->将child传递给this.props.onRef()方法
  }
  handleChildClick=()=>{
    this.setState({info:'通过父组件按钮获取到子组件信息啦啦啦'})
  } 
  render(){
    return <button onClick={this.handleChildClick}>子组件按钮</button>
  }
}

原理:

当在子组件中调用onRef函数时,正在调用从父组件传递的函数。this.props.onRef(this)这里的参数指向子组件本身,父组件接收该引用作为第一个参数:onRef = {ref =>(this.child = ref)}然后它使用this.child保存引用。之后,可以在父组件内访问整个子组件实例,并且可以调用子组件函数。

react官方文档refs转发

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值