组件通信04 -----onRef

通过 props 将子组件的组件实例( this)当作参数,通过回调传到父组件,然后在父组件就可以拿到子组件的实例,就可以调用子组件中国的方法

父组件

import React from 'react'
import Son from './Son'

class Parents extends React.Component {
  sonRef = (ref) => {
    // 在这里拿到子组件的实例
    this.child = ref 
  }
  clearSonInput = () => {
    this.child.clearInput()
  }
  render() {
    return (
      <div>
        <Son onRef={this.sonRef} />
        <button type='primary' onClick={this.clearSonInput}>
          清空
        </button>
      </div>
    )
  }
}
export default Parents

子组件

// 子组件
import React from 'react'

class Son extends React.Component {
  componentDidMount() {
    // 在这将子组件的实例传递给父组件this.props.onRef()方法
    this.props.onRef(this) 
  }
  state = {
    info: 'son',
  }
  handleChange = (e) => {
    this.setState({
      info: e.target.value,
    })
  }
  clearInput = () => {
    this.setState({
      info: '',
    })
  }
  render() {
    return (
      <div>
        <div>{this.state.info}</div>
        <input type='text' onChange={this.handleChange} />
      </div>
    )
  }
}
export default Son

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值