javascript - React 从子组件方法调用父组件方法

标签 javascript reactjs redux-form

<分区>

我有一个子组件,它是一个 Redux 表单,从它的 handleSubmit 方法,我需要在父组件上调用一个方法。我尝试通过将回调作为 Parent 的 Prop 传递来做到这一点,但没有任何反应。

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

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

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

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

最佳答案

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

关于javascript - React 从子组件方法调用父组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557457/

相关文章:

javascript - return 中的样式标签 ()

javascript - 单击时防止触发焦点事件

javascript - 如何在 Redux-form 中有可搜索的下拉菜单

infinite-loop - 在initialValues中设置日期时redux-form无限循环

javascript - jQuery 使用字符串在对象中搜索

javascript - 动态事件处理程序

reactjs - Enzyme,如何通过属性找到wrapper的 child ?

javascript - 将 reactjs 与 requirejs 一起使用

javascript - React Typescript如何发送 Prop 并在子组件中使用它

reactjs - 如何根据事件触发的某些条件以 redux 形式显示或隐藏字段