首页 > 解决方案 > 子类组件调用父类组件的方法

问题描述

我在 App.js 中有一个addNotification()方法,我想在我的其他一些组件中重用它。这里我以AgencyProfile组件为例。如果我从App.js导出addNotification()方法,它将不起作用。如何从其他子组件调用方法addNotification(),例如AgencyProfile?这是我的 App.js 代码

export class App extends React.Component{

.....

        addNotification(title, message, level, time) {
        let dismiss = (time === undefined) ? 0 : time;
        this.notification.addNotification({
            title: title,
            message: message,
            level: level,
            autoDismiss: dismiss
        });
    }
.......

render() {

        return (
            <div>
                <NotificationSystem ref={ref => this.notification = ref}/>
                <AgencyProfile />

            </div>
        );
    }

}

标签: reactjs

解决方案


是的,如果您将函数addNotification作为要在其中重用函数的组件的道具(回调)传递,这是可能的:

应用程序.js:

export class App extends React.Component{

.....

addNotification = (title, message, level, time) => {
        let dismiss = (time === undefined) ? 0 : time;
        this.notification.addNotification({
            title: title,
            message: message,
            level: level,
            autoDismiss: dismiss
        });
    };

.......

render() {
        return (
            <div>
                <NotificationSystem ref={ref => this.notification = ref}/>
                <AgencyProfile onAddNotification={this.addNotification} />
                .....

            </div>
        );
    }
}

在子组件中,我们可以像这样创建一个方法来调用App.js中的addNotification()方法

AgencyProfile.js

showNotification(title, message, level, time){
    this.props.onAddNotification(title, message, level, time);
}

使用此方法从AgencyProfile组件内的任何位置调用addNotification() 。

另一种方法是使addNotification()成为另一个js文件中的可导出函数,然后将其导入要使用它的组件中(但是使用这种方法,您必须this根据要使用它的位置进行绑定):

import addNotification from 'helpers/addNotification';

推荐阅读