react父子组件通信

父组件向子组件通信

  1. 回调函数
goDetail = (msg) => {
    console.log(msg)
}

render() {
    const { item } = this.state
    return(
        <HotItem data={item} goDetail={() => this.goDetail()} />
    )
}

直接把函数传到组件里面,然后组件里面调用this.props.goDetail函数来完成回调

  1. 添加ref属性
init() {
    this.refs.renderListMap.initMap(coordinateX, coordinateY, hotelName, 0)
}

render() {
    return(
        <ListMap ref="renderListMap" />
    )
}

通过给组件设置ref属性,然后就可以使用this.refs.renderListMap...来调用组件里面的方法。

子组件向父组件通信

  1. 回调函数
子组件 ChildComponent.js
<img
    alt=""
    src={imgUrl || defaultImg} onClick={() => this.props.goDetail && this.props.goDetail('hello, world')}
    onError={(e) => { e.target.onerror = null; e.target.src = defaultImg }} />
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容