从子组件方法

时间:2018-03-29 13:32:39

标签: javascript reactjs redux-form

我有一个子组件,它是一个Redux形式,并且从它的handleSubmit方法,我需要在父组件上调用一个方法。我尝试通过将回调作为来自Parent的道具传递而没有任何反应。

我已经看到,只有在子组件上使用事件处理程序直接调用函数时,此方法才有效。

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>
    }
}

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

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

2 个答案:

答案 0 :(得分:1)

在你的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();
}

答案 1 :(得分:0)

我想这会按预期工作。只需将callCloseModal作为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>
    }
}
相关问题