[英]Why does my HTML form still submit when I return false from onsubmit?
[英]Why onSubmit doesnt submit form when i pass it in the form element. But it does submit when I pass it in the button element in React
我有個問題。 順便說一句,我用 React 寫作。 因此,當我在表單元素中傳入 onSubmit 處理程序時,當我單擊“添加待辦事項”時它不會提交表單。 但是,當我將處理程序傳遞給按鈕元素時,它會提交表單嗎? 請參閱下面的代碼。 我已經包含了嵌套在表單中的子組件文件,以防萬一:
// TodoForm,js
import React from "react";
import PrioritySelector from "./PrioritySelector";
import { connect } from "react-redux";
class TodoForm extends React.Component {
state = {
priorityLevel: null
}
/*submit handler to grab input from the input references and store them
in the "todoData" object. Then dispatches an action type and payload
capturing the data. Then clears the input*/
handleSubmit=( e )=> {
e.preventDefault()
const todoTitle = this.getTodoTitle.value;
const description = this.getDescription.value;
const priorityLevel = this.state.priorityLevel;
const todoData = {
id: Math.floor(Math.random()*1000),
todoTitle,
description,
priorityLevel,
editing: false
}
this.props.dispatch({type:"ADD_TODO", todoData })
this.getTodoTitle.value = "";
this.getDescription.value = "";
}
getData=(priorityLevels)=> {
const data = priorityLevels;
this.setState({
priorityLevel: data
})
}
render() {
return(
<div>
<form>
<input type="text" ref={(input)=> this.getTodoTitle=input} placeholder="Enter Todo" required/>
<input type="text" ref={(input)=> this.getDescription=input} placeholder="Enter Description" required/>
<PrioritySelector getData={this.getData} />
<button onClick={this.handleSubmit} type="button">Add Todo</button>
</form>
</div>
)
}
}
export default connect()(TodoForm);
// PrioritySelecter.js
import React from "react";
import $ from "jquery";
import { connect } from "react-redux";
class PrioritySelector extends React.Component {
componentDidMount() {
$("#selector").show();
}
handleSelect =(e)=> {
const priorityLevel = this.getPriorityLevel.value;
this.props.getData(priorityLevel);
console.log(priorityLevel)
}
render() {
return(
<div>
<div className="input-field col s12">
<select onChange={this.handleSelect} ref={(option)=> this.getPriorityLevel = option} id="selector">
<option disabled defaultValue>Choose your option</option>
<option value="1">Low</option>
<option value="2">Medium</option>
<option value="3">High</option>
</select>
</div>
</div>
)
}
}
const mapStateToProps=(state)=> {
return {
priorityLevel: state
}
}
export default connect(mapStateToProps)(PrioritySelector);
您的按鈕是 type="button" 所以它不會提交表單。 將其更改為 type="submit" 並將處理程序放在表單上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.