javascript - 使用父按钮 React 从子触发表单提交
问题描述
我正在尝试通过放置在父组件中的按钮从子组件提交表单。父级是具有下一个按钮的幻灯片,我在幻灯片的一页中显示我的子组件。
我想做的是:当我按下父级的下一个按钮时,我必须转到下一张幻灯片并提交表单子级。
代码:父组件:
import Slider from "react-slick";
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
errors: {}
}
next() {
this.slider.slickNext();
}
previous() {
this.slider.slickPrev();
}
render() {
const settings = {
dots: true,
infinite: false
};
return (
<div>
<Slider ref={c => (this.slider = c)} {...settings}>
<div style={{ textAlign: "center" }} key={1} >
<Child /> //this is the Child I want to submit once I press Next Button
<Button id="btn" className="btn btn-primary float-right " type="submit" onClick={this.next}> Next</Button> //this is the next button which sould trigger the submit from Child
</div>
<div key={2} >
<Page2/>
<Button className="btn btn-primary float-right " id="btn" onClick={() => this.finish()>Finish</Button>
<Button id="btn" className="btn btn-primary float-right " onClick={this.previous}> Previous</Button>
</div>
</Slider>
</div>
);
}
}
子组件:
class Child extends React.Component {
constructor(props) {
super(props)
this.state = {
info: '',
infoID: 0,
valid:false,
errors: {}
}
this.handleValidSubmit = this.handleValidSubmit.bind(this);
this.onChange = this.onChange.bind(this);
}
handleValidSubmit() {
if(valid){
localStorage.setItem("infoID",this.state.infoID);
this.sendIDToServerAPI(infoID);
}else {
localStorage.setItem("infoID",this.state.infoID);
this.saveNewInfoAPI(info);
}
}
render() {
return (
<div }>
<Container fluid >
<Row >
<Col >
<AvForm id="avForm" onValidSubmit={this.handleValidSubmit} onInvalidSubmit=}>
<Label >Info</Label>
<AvField onChange={this.onChange} name="email" placeholder=""Email/>
........
.......
</AvForm>
</Col>
</Row>
</Container>
</div>
);
}
}
我试图最小化这些组件,因为它们太大了,我希望我尝试做的事情足够清楚。谁能帮我一个解决方案/想法?我试图谷歌它,但找不到任何有用的东西。
非常感谢
解决方案
你可以做的是保持一个状态(一个标志),比如提交,它最初是错误的。
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
submit: false
....rest of your code
}
// function to update the submit state
const setFormSubmit = () => this.setState({submit: true})
}
现在您在下一个按钮单击时调用setFormSubmit现在您可以将此状态(提交)传递给您的子组件。并且只要提交为真,您将触发提交表单的方法
您可以通过在子组件中使用 componentDidUpdate 来做到这一点。
componentDidUpdate(prevProps, prevState) {
// if prev submit and current submit prop is unequal and the submit is true
if ((prevProps.submit !== this.props.submit) && this.props.submit) {
// Call method to submit form
}
}
推荐阅读
- c++ - 在具有依赖关系的项目中进行协作
- vue.js - Vue js 错误信息只显示一次。试图弄清楚每次出现错误时如何显示它
- c++ - 指向明确创建的对象的智能指针
- poco-libraries - Poco Thread 如何避免使用 Join
- ruby-on-rails - 使用 Ruby on Rails 提交后出现路由错误
- css - Safari 开发者工具在调试 Ipad 时不显示自定义 CSS
- websphere - 自动化脚本中未定义隐式变量
- reactjs - 弹出框中的按钮“更多”不适用于 React hook useState
- client-server - Apache Geode - 在基于 DUnit 的测试服务器/远程服务器上使用来自客户端的相同代码创建区域
- php - wp_remote_post 不发送帖子数据