react组件通信

子组件获取父组件

可通过props接收

<ChildList parentRef={parentRef} name={name}></ChildList>

父组件获取子组件

useRef将ref绑定到某个子组件标签上,用以获取整个子组件的方法和参数
useImperativeHandle: 可以自定义暴露给父组件的方法或者变量

父组件

import React, { useState, useRef } from 'react'
import ChildList from './ChildList'

export default () => {
    let parentRef = useRef(null)
    const [name, setName] = useState('li')
    return <div>
        <ChildList parentRef={parentRef} name={name}></ChildList>
        <button onClick={() => {
            console.log("parentRef", parentRef)
        }}>获取子组件</button>
    </div>
}

子组件

import React, { useImperativeHandle, forwardRef } from 'react'

export default forwardRef((props) => {
    console.log("props", props)
    const { parentRef } = props;
    useImperativeHandle(parentRef, () => {
        return {
            childFn
        }
    })
    console.log(parentRef)
    const childFn = () => {
        console.log('子组件方法')
    }
    return <div>
        <div ref={parentRef} />
    </div>
})

类组件中父组件获取子组件

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

// 父组件
class Parent extends React.Component {
  handleClick=()=>{
    this.child.handleChildClick() // -> 通过this.child可以拿到child所有状态和方法
  }
  render() {
    return <div>
      <ChildList onRef={(ref) => {this.child = ref}} />
      <button onClick={this.handleClick}>父组件按钮</button>
    </div>
  }
}

// 子组件
class ChildList extends React.Component {
  constructor(props) {
    super(props)
  }
  componentDidMount(){
    this.props.onRef(this)// ->将child自己传递给this.props.onRef()方法
  }
  handleChildClick=()=>{
    console.log('通过父组件按钮获取到子组件信息啦啦啦')
  } 
  render(){
    return <div>我是子组件</div>
  }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值