Javascript 如何从react中的另一个组件调用组件引用?

Javascript 如何从react中的另一个组件调用组件引用?,javascript,reactjs,Javascript,Reactjs,我使用库,发现我的代码或多或少是这样的 import React from 'react'; import Notification from 'react-notification-system'; class Notif extends React.Component { constructor(props) { super(props); this.notificationSystem = null; } componentDidMount() {

我使用库,发现我的代码或多或少是这样的

import React from 'react';
import Notification from 'react-notification-system';

class Notif extends React.Component {

  constructor(props) {
    super(props);

    this.notificationSystem = null;
  }

  componentDidMount() {
    // how to export this?
    this.notificationSystem = this.refs.notificationSystem;
  }

  render() {
    return <Notification ref="notificationSystem" />;
  }

}

export default Notif;
从“React”导入React;
从“反应通知系统”导入通知;
类Notif扩展React.Component{
建造师(道具){
超级(道具);
this.notificationSystem=null;
}
componentDidMount(){
//如何出口?
this.notificationSystem=this.refs.notificationSystem;
}
render(){
返回;
}
}
出口违约通知;
如何导出该通知系统,以便在任何地方都可以使用它?

有两种方法:

  • 使用全局小部件
  • 只需添加一个全局小部件,如下所示

    var _component
    
    export function set(component) {
        _component = component
    }
    
    export function get() {
        return _component
    }
    
    然后在
    AppComponent
    中注册它:

    import {set} from './notify'
    class App extends React.Component {
        componentDidMount() {
            set(this.refs.notificationSystem)
        }
    }
    
    在任何其他组件中,将其称为:

    import {get} from './notify'
    class AnyComponent extends React.Component {
        alert() {
            get().doSomething()
        }
    }
    
  • 使用react上下文将其存储为所有组件的全局道具
  • 两种方式:

  • 使用全局小部件
  • 只需添加一个全局小部件,如下所示

    var _component
    
    export function set(component) {
        _component = component
    }
    
    export function get() {
        return _component
    }
    
    然后在
    AppComponent
    中注册它:

    import {set} from './notify'
    class App extends React.Component {
        componentDidMount() {
            set(this.refs.notificationSystem)
        }
    }
    
    在任何其他组件中,将其称为:

    import {get} from './notify'
    class AnyComponent extends React.Component {
        alert() {
            get().doSomething()
        }
    }
    
  • 使用react上下文将其存储为所有组件的全局道具

  • 你能用一个例子解释一下上下文吗?所以我可以把你的答案标记为
    done
    ,谢谢。代码太长了,没有测试我不能发布。你们可以用官方文件来做:是的,事实上我已经读到了上下文,但我需要更新它,对吗?在触发
    componentDidMount
    时,我需要建议如何处理。有两种方法:第一种是在
    getChildContext()
    中返回引用的对象,第二种是在应用程序装载到flush context时触发更新事件。也许这是帮助:好的,我已经用上下文完成了,谢谢你的帮助。你能用一个例子解释一下上下文吗?所以我可以把你的答案标记为
    done
    ,谢谢。代码太长了,没有测试我不能发布。你们可以用官方文件来做:是的,事实上我已经读到了上下文,但我需要更新它,对吗?在触发
    componentDidMount
    时,我需要建议如何处理。有两种方法:第一种是在
    getChildContext()
    中返回引用的对象,第二种是在应用程序装载到flush context时触发更新事件。也许这是帮助:好的,我已经使用上下文完成了,谢谢你的帮助。为什么你只想要引用,而不想要
    Notif
    组件?为什么你只想要引用,而不想要
    Notif
    组件?