React - 表单提交后清除输入值
React - clearing an input value after form submit
我遇到了一个相当愚蠢的问题。我正在创建我的第一个 React 应用程序,我遇到了一个小问题,我在提交表单后无法清除我的输入值。尝试用谷歌搜索这个问题,在这里找到了一些类似的线程,但我无法解决这个问题。我不想更改 component/application 的状态,只是将输入的值更改为空字符串。我尝试清除 onHandleSubmit()
函数中的输入值,但出现错误:
"Cannot set property 'value' of undefined".
我的 SearchBar 组件:
import React, { Component } from "react";
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
this.onHandleChange = this.onHandleChange.bind(this);
this.onHandleSubmit = this.onHandleSubmit.bind(this);
}
render() {
return (
<form>
<input
id="mainInput"
onChange={this.onHandleChange}
placeholder="Get current weather..."
value={this.state.city}
type="text"
/>
<button onClick={this.onHandleSubmit} type="submit">
Search!
</button>
</form>
);
}
onHandleChange(e) {
this.setState({
city: e.target.value
});
}
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
}
export default SearchBar;
由于你的input域是一个受控元素,你不能直接改变input域的值而不修改状态。
也在
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
this.mainInput
不引用输入,因为 mainInput 是一个 id
,您需要指定对输入
的引用
<input
ref={(ref) => this.mainInput= ref}
onChange={this.onHandleChange}
placeholder="Get current weather..."
value={this.state.city}
type="text"
/>
在您当前的状态下,最好的方法是清除状态以清除输入值
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({city: ""});
}
但是,如果出于某种原因您仍然希望在提交表单时保持值的状态,您宁愿使输入不受控制
<input
id="mainInput"
onChange={this.onHandleChange}
placeholder="Get current weather..."
type="text"
/>
并更新状态 onChange
中的值,并且 onSubmit
使用 ref
清除输入
onHandleChange(e) {
this.setState({
city: e.target.value
});
}
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
话虽如此,我认为保持状态不变没有任何意义,所以第一个选项应该是要走的路。
您有一个受控组件,其中 input
值由 this.state.city
确定。因此,一旦您提交,您必须清除您的状态,这将自动清除您的输入。
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
this.mainInput
实际上没有指向任何东西。由于您使用的是受控组件(即输入值是从状态获得的),您可以将 this.state.city
设置为 null:
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({ city: '' });
}
在您的 onHandleSubmit
函数中,像这样再次将您的状态设置为 {city: ''}
:
this.setState({ city: '' });
上面的答案是不正确的,它们都会 运行 提交是否成功......你需要编写一个错误组件来接收任何错误然后检查状态是否有错误,如果没有则清除表格....
使用 .then()
示例:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
setTicketData({
ticketType: "IT",
ticketSubject: "",
ticketDescription: "",
itHelpType: "",
ticketPriority: ""
})
})
};
这是我要清除并在状态 1st STEP 中创建它的值
state={
TemplateCode:"",
}
创建 Button 的 submitHandler 函数或您想要的第 3 步
submitHandler=()=>{
this.clear();//this is function i made
}
这是清除函数最后一步
clear = () =>{
this.setState({
TemplateCode: ""//simply you can clear Templatecode
});
}
当点击按钮模板代码清除第二步
<div class="col-md-12" align="right">
<button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save
</button>
</div>
如果你想清除表单的字段并且你使用的是组件函数而不是 Class 组件你可以做到这很容易
假设我们在表单标题、价格和日期中有三个输入
我们希望在从用户那里获得这些值后我们希望清除字段
import React, { useState } from "react";
function ClearForm() {
// our initial states
const [enteredTitle, setEnteredTitle] = useState("");
const [enteredPrice, setEnteredPrice] = useState("");
const [enteredDate, setEnteredDate] = useState("");
// this function for get our title value from the user.
function titleChangeHandler(event) {
setEnteredTitle(event.target.value);
}
// this function for get our price value from the user.
// price that we will get is string we have to convert it to number simply add + in front of the event.target.value like this +event.target.value
function priceChangeHandler(event) {
setEnteredPrice(+event.target.value);
}
// this function for get our date value from the user.
// don't forget we we will get it as string .
function dateChangeHandler(event) {
setEnteredDate(event.target.value);
}
// here we will gather our data title, price, and date
let expensesData = {
title: enteredTitle,
price: enteredPrice,
date: new Date(enteredDate), // we have to convert our date form string to date
};
// this function will clear our fields
// we will call it inside submitFormHandler
// after submit form we we will call submitFormHandler function and we will pass event as parameter to clearFields
function clearFields(event) {
// we have to convert event.target to array
// we use from method to convert event.target to array
// after that we will use forEach function to go through every input to clear it
Array.from(event.target).forEach((e) => (e.value = ""));
}
// this function to submit form
function submitFormHandler(event) {
// we don't want our page to refresh
event.preventDefault();
// print expenses data
console.log(expensesData)
// clear the fields
clearFields(event);
//update our states
// why we should update our states to empty string
// if we have not done it we clears the fields but we still have the data in our states
// if the user submit the form without any data but our states still has the previous data
//update title
setEnteredTitle("");
//update title
setEnteredPrice("");
//update title
setEnteredDate("");
}
return (
// our form
<form onSubmit={submitFormHandler}>
<label>Title</label>
<input type="text" onChange={titleChangeHandler} />
<label>Price</label>
<input
type="number"
onChange={priceChangeHandler}
/>
<label>Date</label>
<input type="date" onChange={dateChangeHandler} />
<button type="submit">submit</button>
</form>
);
}
export default ClearForm;
使用 useState 钩子清除字段
function clearForm() {
// our initial states
const [enteredTitle, setEnteredTitle] = useState("");
const [enteredAmount, setEnteredAmount] = useState("");
const [enteredDate, setEnteredDate] = useState("");
// this function for get our title value from the user.
function titleChangeHandler(event) {
setEnteredTitle(event.target.value);
}
// this function for get our amount value from the user.
// amount that we will get is string we have to convert it to number simply add + in front of the event.target.value like this +event.target.value
function amountChangeHandler(event) {
setEnteredAmount(+event.target.value);
}
// this function for get our date value from the user.
// don't forget we we will get it as string .
function dateChangeHandler(event) {
setEnteredDate(event.target.value);
}
// here we will gother our data title, price, and date
let expensesData = {
title: enteredTitle,
amount: enteredAmount,
date: new Date(enteredDate), // we have to convert our date form string to date
};
// this function to submit form
function submitFormHandler(event) {
// we don't want our page to refresh
event.preventDefault();
// princt expensesData
console.log( expensesData)
//update our states
//update title
setEnteredTitle("");//enteredTitle="";
//update title
setEnteredAmount("");//enteredAmount="";
//update title
setEnteredDate("");//enteredDate="";
}
return (
// our form
<form onSubmit={submitFormHandler}>
<label>Title</label>
<input
type="text"
// after submit our form we will clier our title field automatically
value={enteredTitle}//enteredTitle="";
onChange={titleChangeHandler}
/>
<label>Amount</label>
<input
type="number"
// after submit our form we will clier our amount field automatically
value={enteredAmount}//enteredAmount="";
onChange={amountChangeHandler}
/>
<label>Date</label>
<input
type="date"
// after submit our form we will clier our date field automatically
value={enteredDate}//enteredDate="";
onChange={dateChangeHandler}
/>
<button type="submit">submit</button>
</form>
);
}
export default clearForm;
简单
import React, { useState } from "react";
export default function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
function handleSubmit(e) {
e.preventDefault();
console.log(email, password);
// clearing the values
setEmail("");
setPassword("");
}
return (
<form>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" onClick={handleSubmit}>
Login
</button>
</form>
);
}
我遇到了一个相当愚蠢的问题。我正在创建我的第一个 React 应用程序,我遇到了一个小问题,我在提交表单后无法清除我的输入值。尝试用谷歌搜索这个问题,在这里找到了一些类似的线程,但我无法解决这个问题。我不想更改 component/application 的状态,只是将输入的值更改为空字符串。我尝试清除 onHandleSubmit()
函数中的输入值,但出现错误:
"Cannot set property 'value' of undefined".
我的 SearchBar 组件:
import React, { Component } from "react";
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
this.onHandleChange = this.onHandleChange.bind(this);
this.onHandleSubmit = this.onHandleSubmit.bind(this);
}
render() {
return (
<form>
<input
id="mainInput"
onChange={this.onHandleChange}
placeholder="Get current weather..."
value={this.state.city}
type="text"
/>
<button onClick={this.onHandleSubmit} type="submit">
Search!
</button>
</form>
);
}
onHandleChange(e) {
this.setState({
city: e.target.value
});
}
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
}
export default SearchBar;
由于你的input域是一个受控元素,你不能直接改变input域的值而不修改状态。
也在
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
this.mainInput
不引用输入,因为 mainInput 是一个 id
,您需要指定对输入
<input
ref={(ref) => this.mainInput= ref}
onChange={this.onHandleChange}
placeholder="Get current weather..."
value={this.state.city}
type="text"
/>
在您当前的状态下,最好的方法是清除状态以清除输入值
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({city: ""});
}
但是,如果出于某种原因您仍然希望在提交表单时保持值的状态,您宁愿使输入不受控制
<input
id="mainInput"
onChange={this.onHandleChange}
placeholder="Get current weather..."
type="text"
/>
并更新状态 onChange
中的值,并且 onSubmit
使用 ref
onHandleChange(e) {
this.setState({
city: e.target.value
});
}
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
话虽如此,我认为保持状态不变没有任何意义,所以第一个选项应该是要走的路。
您有一个受控组件,其中 input
值由 this.state.city
确定。因此,一旦您提交,您必须清除您的状态,这将自动清除您的输入。
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
this.mainInput
实际上没有指向任何东西。由于您使用的是受控组件(即输入值是从状态获得的),您可以将 this.state.city
设置为 null:
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({ city: '' });
}
在您的 onHandleSubmit
函数中,像这样再次将您的状态设置为 {city: ''}
:
this.setState({ city: '' });
上面的答案是不正确的,它们都会 运行 提交是否成功......你需要编写一个错误组件来接收任何错误然后检查状态是否有错误,如果没有则清除表格....
使用 .then()
示例:
const onSubmit = e => {
e.preventDefault();
const fd = new FormData();
fd.append("ticketType", ticketType);
fd.append("ticketSubject", ticketSubject);
fd.append("ticketDescription", ticketDescription);
fd.append("itHelpType", itHelpType);
fd.append("ticketPriority", ticketPriority);
fd.append("ticketAttachments", ticketAttachments);
newTicketITTicket(fd).then(()=>{
setTicketData({
ticketType: "IT",
ticketSubject: "",
ticketDescription: "",
itHelpType: "",
ticketPriority: ""
})
})
};
这是我要清除并在状态 1st STEP 中创建它的值
state={
TemplateCode:"",
}
创建 Button 的 submitHandler 函数或您想要的第 3 步
submitHandler=()=>{
this.clear();//this is function i made
}
这是清除函数最后一步
clear = () =>{
this.setState({
TemplateCode: ""//simply you can clear Templatecode
});
}
当点击按钮模板代码清除第二步
<div class="col-md-12" align="right">
<button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save
</button>
</div>
如果你想清除表单的字段并且你使用的是组件函数而不是 Class 组件你可以做到这很容易 假设我们在表单标题、价格和日期中有三个输入 我们希望在从用户那里获得这些值后我们希望清除字段
import React, { useState } from "react";
function ClearForm() {
// our initial states
const [enteredTitle, setEnteredTitle] = useState("");
const [enteredPrice, setEnteredPrice] = useState("");
const [enteredDate, setEnteredDate] = useState("");
// this function for get our title value from the user.
function titleChangeHandler(event) {
setEnteredTitle(event.target.value);
}
// this function for get our price value from the user.
// price that we will get is string we have to convert it to number simply add + in front of the event.target.value like this +event.target.value
function priceChangeHandler(event) {
setEnteredPrice(+event.target.value);
}
// this function for get our date value from the user.
// don't forget we we will get it as string .
function dateChangeHandler(event) {
setEnteredDate(event.target.value);
}
// here we will gather our data title, price, and date
let expensesData = {
title: enteredTitle,
price: enteredPrice,
date: new Date(enteredDate), // we have to convert our date form string to date
};
// this function will clear our fields
// we will call it inside submitFormHandler
// after submit form we we will call submitFormHandler function and we will pass event as parameter to clearFields
function clearFields(event) {
// we have to convert event.target to array
// we use from method to convert event.target to array
// after that we will use forEach function to go through every input to clear it
Array.from(event.target).forEach((e) => (e.value = ""));
}
// this function to submit form
function submitFormHandler(event) {
// we don't want our page to refresh
event.preventDefault();
// print expenses data
console.log(expensesData)
// clear the fields
clearFields(event);
//update our states
// why we should update our states to empty string
// if we have not done it we clears the fields but we still have the data in our states
// if the user submit the form without any data but our states still has the previous data
//update title
setEnteredTitle("");
//update title
setEnteredPrice("");
//update title
setEnteredDate("");
}
return (
// our form
<form onSubmit={submitFormHandler}>
<label>Title</label>
<input type="text" onChange={titleChangeHandler} />
<label>Price</label>
<input
type="number"
onChange={priceChangeHandler}
/>
<label>Date</label>
<input type="date" onChange={dateChangeHandler} />
<button type="submit">submit</button>
</form>
);
}
export default ClearForm;
使用 useState 钩子清除字段
function clearForm() {
// our initial states
const [enteredTitle, setEnteredTitle] = useState("");
const [enteredAmount, setEnteredAmount] = useState("");
const [enteredDate, setEnteredDate] = useState("");
// this function for get our title value from the user.
function titleChangeHandler(event) {
setEnteredTitle(event.target.value);
}
// this function for get our amount value from the user.
// amount that we will get is string we have to convert it to number simply add + in front of the event.target.value like this +event.target.value
function amountChangeHandler(event) {
setEnteredAmount(+event.target.value);
}
// this function for get our date value from the user.
// don't forget we we will get it as string .
function dateChangeHandler(event) {
setEnteredDate(event.target.value);
}
// here we will gother our data title, price, and date
let expensesData = {
title: enteredTitle,
amount: enteredAmount,
date: new Date(enteredDate), // we have to convert our date form string to date
};
// this function to submit form
function submitFormHandler(event) {
// we don't want our page to refresh
event.preventDefault();
// princt expensesData
console.log( expensesData)
//update our states
//update title
setEnteredTitle("");//enteredTitle="";
//update title
setEnteredAmount("");//enteredAmount="";
//update title
setEnteredDate("");//enteredDate="";
}
return (
// our form
<form onSubmit={submitFormHandler}>
<label>Title</label>
<input
type="text"
// after submit our form we will clier our title field automatically
value={enteredTitle}//enteredTitle="";
onChange={titleChangeHandler}
/>
<label>Amount</label>
<input
type="number"
// after submit our form we will clier our amount field automatically
value={enteredAmount}//enteredAmount="";
onChange={amountChangeHandler}
/>
<label>Date</label>
<input
type="date"
// after submit our form we will clier our date field automatically
value={enteredDate}//enteredDate="";
onChange={dateChangeHandler}
/>
<button type="submit">submit</button>
</form>
);
}
export default clearForm;
简单
import React, { useState } from "react";
export default function Login() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
function handleSubmit(e) {
e.preventDefault();
console.log(email, password);
// clearing the values
setEmail("");
setPassword("");
}
return (
<form>
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit" onClick={handleSubmit}>
Login
</button>
</form>
);
}