簡體   English   中英

如何在反應中從另一個組件調用組件引用?

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

我使用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;

如何導出該notificationSystem以便可以在任何地方使用它?

兩種方式:

  1. 使用全局小部件。

只需添加一個全局小部件,如下所示。

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()
    }
}
  1. 使用react上下文將其存儲為所有組件的全局道具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM