简体   繁体   中英

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.

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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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