[英]React hook: How to call Modal component from another component in react
[英]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
以便可以在任何地方使用它?
兩種方式:
只需添加一個全局小部件,如下所示。
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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.