基本代码如下,但表单会提交并重新加载。为什么?
import React from 'react';
class TestSubmitComponent extends React.Component {
constructor(props) {
super(props);
}
formSubmitHandler = (e) => {
e.preventDefault(); //should prevent submit, and continue below?
console.log(e);
console.log('hello world ! why this does NOT show in console?!')
return false;
}
render() {
return(
<form method="POST" action="/">
<div onSubmit={this.formSubmitHandler}>
<h1>Select a file to upload</h1>
<input type="file" accept=".txt" name="ctlFileInput"></input>
<p/>
<input type="submit" value="Click to submit" />
</div>
</form>
)
}
}
export default TestSubmitComponent;
最佳答案
您的formSubmitHandler()
方法实际上并未触发,因此自 onSubmit()
以来每次表单提交都会发生页面刷新的默认行为回调需要绑定(bind)到您的 form
元素:
<form onSubmit={this.formSubmitHandler}>
此外,我会删除 POST
请求/
您的服务器上的路由。这是在您的 form
中定义的元素,但这不是我们想要的,因为这将调用您的服务器,而不是触发您的 formSubmitHandler()
方法。也许你可以尝试以下方法:
import React from 'react';
class TestSubmitComponent extends React.Component {
constructor(props) {
super(props);
}
formSubmitHandler = (e) => {
e.preventDefault(); //should prevent submit, and continue below?
console.log(e);
console.log('hello world ! why this does NOT show in console?!')
return false;
}
render() {
return(
<form onSubmit={this.formSubmitHandler}>
<div>
<h1>Select a file to upload</h1>
<input type="file" accept=".txt" name="ctlFileInput"></input>
<p/>
<input type="submit" value="Click to submit" />
</div>
</form>
)
}
}
export default TestSubmitComponent;
希望有帮助!
关于reactjs - 为什么 e.preventDefault() 在 React 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55485461/