基本React表单提交刷新整个页面 [英] Basic React form submit refreshes entire page
问题描述
我正在尝试创建一个输入表单,该表单将信息存储在组件的状态变量中,然后在屏幕上输出该变量.我阅读了有关受控组件的文档,这就是我在这里所尝试的.
I'm trying to create an input form that stores information in a component's state variable, then outputs that variable on the screen. I read the docs on controlled components, and that's what I'm attempting here.
这里的主要问题是,当我单击提交"时,正确的文本出现在屏幕上,但是随后整个页面都会刷新,我不确定为什么.从我在网上阅读的内容来看, refs
似乎是一种解决方案,但我的理解是我可以使用该组件或受控组件.
My main issue here is when I click submit, the correct text appears on the screen, but then the entire page refreshes and I'm not sure why. From what I've read online, refs
appear to be a solution, but my understanding is that I can use either that, or controlled components.
class InputField extends React.Component {
constructor(props) {
super(props);
this.state = {
itemName: "",
storedItemName: "",
};
this.handleNameChange = this.handleNameChange.bind(this);
this.afterSubmission = this.afterSubmission.bind(this);
}
handleNameChange(event) {
this.setState({
itemName: event.target.value
});
}
afterSubmission(event) {
let name = this.state.itemName;
this.setState ({
storedItemName:this.state.itemName
}, function() {
alert(this.state.storedItemName); // Shows the right value!
});
}
render() {
return(
<div>
<form onSubmit = {this.afterSubmission}>
<label> Item Name:
<input
type = "text"
name = "itemName"
value = {this.state.itemName}
onChange = {this.handleNameChange}
/></label>
<input type = "submit" value = "Submit" />
</form>
<div className = "itemList">
<p>Hi</p>
{this.state.storedItemName}
</div>
</div>
);
}
推荐答案
只需调用 event.preventDefault
方法即可防止表单的默认行为
Just call event.preventDefault
method to prevent default behavior of form
afterSubmission(event) {
event.preventDefault();
let name = this.state.itemName;
this.setState ({
storedItemName:this.state.itemName
}, function() {
alert(this.state.storedItemName); // Shows the right value!
}
}
这篇关于基本React表单提交刷新整个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!