有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/