K
K
konstantinst132020-07-21 00:31:56
JavaScript
konstantinst13, 2020-07-21 00:31:56

How to pass a method with this from one component to another?

I need to pass the save method of the Editor component from the Editor component to the Modal component. But when passing this is lost and gives undefined in the console. I bind the context using bind in the constructor of the Editor class - it doesn't work. And in
Editor:

import React, {Component} from 'react';
import Modal from '../modal';
import $ from 'jquery';

export default class Editor extends Component {
    constructor() {
        super();
      
        this.state = {
            pageList: [],
            newPageName: '',
            loading: true
        }
        this.save = this.save.bind(this); //не работает
    }

 render() { 
        const {pageList, loading} = this.state;
        const modal = true;
        return ( 
            <> 
            <ConfirmModal modal={modal} target={'modal-save'} method={this.save} />
            </>   
        )
    }


modal:
import React from 'react';

const ConfirmModal = ({modal, target, method}) => {
    return (
    <div id={target} uk-modal={modal.toString()}>
        <div>
                <h2>Сохранение</h2>
                
                <p>Вы действительно хотите сохранить изменения?</p>
                
                <p>
                   <button>Отменить</button>
                   <button onClick=
                    {
                        () => method
                           (
                            // ******* Уведомление об успешном сохранении
                                ()=>{
                                          UIkit.notification({message: 'Успешно сохранено!', status: 'success'});
                                      },
                            // ******* Уведомление об ошибке
                                ()=>{
                                           UIkit.notification({message: 'Ошибка сохранения!', status: 'danger'})                                                       
                                      }
                            )
                     }>Сохранить</button>           
                </p>
        </div>
    </div>
    )
}

export default ConfirmModal;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2020-07-21
@konstantinst13

It's not entirely clear what you mean by not working? I don't see the implementation of the save method. And surely this is undefined and not the method itself? Instead of bind, you can immediately define the save method as an arrow function, then there will be no problems with this.
From the current code, it's hard to understand what your problem is. What you are doing is a standard task - passing a function to a component https://ru.reactjs.org/docs/faq-functions.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question