带标签的父页面示例
import {Tab, Tabs } from 'react-bootstrap';
import * as Survey from "survey-react";
import "survey-react/survey.css";
import SectionA from './SectionA';
import SectionB from './SectionB';
//Tabs
<Tabs activeKey={this.state.activeTab} onSelect={this.handleSelect}>
<Tab eventKey={1} title="CORE SEC A."><SectionA setClick={click => this.clickChild = click}/></Tab>
<Tab eventKey={2} title="CORE SEC B."><SectionB setClick={click => this.clickChild = click}/></Tab>
...
</Tabs>
//button function
<button onClick={() => this.clickChild()}>Validate All</button>
子页面示例
componentDidMount() {
this.props.setClick(this.getValidation);
}
getValidation() {
survey.currentPage.hasErrors();
}
问题在于单击按钮
Validate All
时,它仅调用第二个Child的click事件/函数。如何在不创建更多按钮的情况下将其称为多个子级?
最佳答案
我会用ref
父母示例
class Parent extends React.Component {
constructor(props){
super(props);
this.childA = React.createRef();
this.childB = React.createRef();
//....
}
onClick = () => {
this.childA.current.getValidation();
this.childB.current.getValidation();
//....
};
render(){ return (
<React.Fragment>
....
<button onClick={this.onClick}>Validate Complete</button>
<Tab eventKey={1} title="CORE SEC A."><SectionA ref={this.childA}/></Tab>
<Tab eventKey={2} title="CORE SEC B."><SectionB ref={this.childB}/></Tab>
</React.Fragment>
)}
}
子示例(每个子组件页面中的put方法)
getValidation() {
console.log('Section A validation'); // Section B etc... for other component files
survey.currentPage.hasErrors();
}
我对所有这些代码重复都不感到兴奋-好像您不需要一堆文件即可。根据我所看到的,这应该对您有用。如果某些React / Javascript大师有更好的解决方案,我也很好奇。问题在于没有代码库来了解实际情况。
关于javascript - 一键式 react JS Parent以调用多个子代的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617073/