forms - 在兄弟组件 Reactjs 中调用函数

标签 forms reactjs components submit

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

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

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

提前致谢。

最佳答案

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

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

A:

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()

关于forms - 在兄弟组件 Reactjs 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44450901/

相关文章:

javascript - 将 props 传递给服务器中 React 路由器的处理程序

java - 从另一个类访问 Swing 组件

javascript - 为什么键为空?尽管我创建了它

ajax - 使用 Polymer 实现声明式集合渲染的最佳方法是什么?

java - 将 Java 对象从一个 Struts 操作传递到另一个

javascript - jQuery 或 Javascript 在提交时解析查询字符串

windows - Windows 需要 CHR(10) 和 CHR(13) 吗?

reactjs - 如何通过 enzyme 中的选择器找到正下方的元素

php - 交响乐2 : How to concatenate multiple fields into one in a form

reactjs - 在 NestJS 中连接后,Socket.io 客户端断开连接