[英]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.