从子类组件调用父类组件的方法

时间:2019-09-20 14:54:32

标签: reactjs

我在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>
        );
    }

}

2 个答案:

答案 0 :(得分:2)

是的,如果您将函数addNotification用作对要在其中重用该函数的组件的支持(回调),这是可能的:

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 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';

答案 1 :(得分:0)

您无法真正导出/导入类似的功能。如果您不希望将它作为树传递下来,那么最好的选择是使用react的上下文https://reactjs.org/docs/context.html。然后,无需导入功能,而只需从上下文中获取它即可。