【问题标题】:Call a function in a sibling component Reactjs在兄弟组件 Reactjs 中调用函数
【发布时间】:2017-11-11 01:33:23
【问题描述】:

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

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

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

提前致谢。

【问题讨论】:

    标签: forms reactjs components submit


    【解决方案1】:

    您可以从孩子与父母沟通,反之亦然。

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

    答:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-13
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多