来自子组件方法的React呼叫呼叫父部件方法



我有一个子组件,该组件是redux表单,从其handlesubmit方法中,我需要在父组件上调用一种方法。我尝试通过将回调作为父母的道具来做到这一点。

我已经看到,只有当一个函数直接与儿童组件上的事件处理程序调用时,此方法才起作用。

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };
    callCloseModal = () => {
        this.props.closeModal();
    }
    handleFormSubmit (values) {
        this.callCloseModal()    
    }
    render() {
         <form onSubmit= 
            {handleSubmit(this.handleFormSubmit.bind(this))}>
            .....
         </form>
    }
}
class Parent extends React.Component {
      constructor (props) {
        super(props)
        this.state = {
          modalOpen: false,
        }
      }
     .....
    handleModalClose() {
        this.setState({ modalOpen: false })
    }
    render() {
          <Child closeModal={this.handleModalClose}> {this.props.children}</Child>
    }
}

如何从子组件上的方法中调用父组件上的方法?

编辑:该方法是正确的,但它更高(祖父母组件(

在您的OnSubmit处理程序中:

render() {
     <form onSubmit= 
        {handleSubmit(this.handleFormSubmit.bind(this))}>
        .....
     </form>
}

您调用handleFormSubmit,但在其定义中:

handleFormSubmit (values) {
    this.callCloseModal    
}

您仅引用callCloseModal。注意callCloseModal定义为箭头函数:

callCloseModal = () => {
    this.props.closeModal();
}

因此您需要称呼它。尝试:

handleFormSubmit (values) {
    this.callCloseModal();
}

我想这将按预期工作。只需呼叫call call closemodal作为handleformsubmit中的函数

class Child extends React.Component {
    constructor(props) {
        super(props);
    };
    callCloseModal = () => {
        // ideally you want to check if props is a func
        if (typeof this.props.closeModal === 'function') {
            this.props.closeModal();
        }
    }
    handleFormSubmit = (values) => { // no need to mix binding with arrow funcs
        this.callCloseModal() // should be calling as a function
    }
    render() {
         <form onSubmit= 
            {handleSubmit(this.handleFormSubmit)}>
            .....
         </form>
    }
}

您只需要从此

更改功能
callCloseModal = () => {
    this.props.closeModal();
}

到这个

callCloseModal = () => {
    this.props.handleModalClose();
}

让我知道您是否遇到其他问题。

最新更新