简体   繁体   English

如何在反应中从另一个组件调用组件引用?

[英]How to call component reference from another component in react?

I use react-notification-system library, and found my code more or less like this. 我使用react-notification-system库,或多或少地发现我的代码是这样的。

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;

How can I export that notificationSystem so I can use it everywhere? 如何导出该notificationSystem以便可以在任何地方使用它?

Two ways: 两种方式:

  1. Use global widget. 使用全局小部件。

Just add a global widget as follow. 只需添加一个全局小部件,如下所示。

var _component

export function set(component) {
    _component = component
}

export function get() {
    return _component
}

And then in your AppComponent register it: 然后在您的AppComponent注册它:

import {set} from './notify'
class App extends React.Component {
    componentDidMount() {
        set(this.refs.notificationSystem)
    }
}

In any other component, call it: 在任何其他组件中,调用它:

import {get} from './notify'
class AnyComponent extends React.Component {
    alert() {
        get().doSomething()
    }
}
  1. Use react context to store it as a global props for all component. 使用react上下文将其存储为所有组件的全局道具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM