在兄弟组件 Reactjs 中调用一个函数

Call a function in a sibling component Reactjs

有 3 个组件。第一个是名为A的父组件。其他是X和Y。

X 是一个带有保存按钮的工具栏组件。 Y 是一个具有一些输入(显然)的 Form 组件。而且都是A导入渲染的。

所以我想做的是,当单击 X 中的保存按钮时,我希望提交 B 中的表单。

提前致谢。

您可以从 child 与 parent 通信,反之亦然。

您需要做的是将处理程序从组件 A 传递给组件 X,然后在该处理程序中使用 refs 您可以访问 Child 组件表单并触发提交,如

甲:

class A extends React.Component {
    constructor(props) {
        super(props);
    }
    buttonSubmit = () => {
           this.Yform.childForm.submit()

    }
    render() {
          return <div>
                <X triggerSubmit={this.buttonSubmit}/>
                <Y ref={(form) => this.Yform = form}/>
           </div>
    }
}

X

class X extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <button onClick={() => this.props.triggerSubmit()}>Submit</button>
           </div>
    }
}

是:

class Y extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <form ref={(childForm) => {this.childForm = childForm}}>
                    ...
                </form>
           </div>
    }
}

如果您使用的是 Redux,那么您需要像

这样调用 onSubmit
  this.YForm.getWrappedInstance().submit()