我想在按下回车键时提交表单,但如果我使用 onSubmit={() => this.onSearchClick(this)}
这是我的函数,我需要运行所有它它是否将表单放入我不希望发生的 url 中,我需要做的就是让它运行该函数,该函数将执行 api 调用。
我的代码是这样的
<form>
<h1>Search</h1>
<hr />
<TextField floatingLabelText="Case ID" name="caseid" onChange={this.handleChange} />
<br />
<TextField floatingLabelText="Title" name="title" value={this.state.title} onChange={this.handleChange} />
<br />
<TextField floatingLabelText="Forename" name="forename" value={this.state.forename} onChange={this.handleChange} />
<br />
<TextField floatingLabelText="Surname" name="surname" value={this.state.surname} onChange={this.handleChange} />
<br />
<TextField floatingLabelText="Postcode" name="postcode" value={this.state.postcode} onChange={this.handleChangePost} />
<br />
<TextField floatingLabelText="Telephone Number" name="telephone" onChange={this.handleChange} />
<br />
<TextField floatingLabelText="Email Address" name="email" value={this.state.email} onChange={this.handleChange} />
<br />
{this.state.isLoggedIn ? <RaisedButton label="Search" onClick={() => this.onSearchClick(this)} primary={true} /> : <RaisedButton label="Search Disabled" primary={true} />}
{this.state.isLoggedIn ? <RaisedButton label="New Entry" onClick={() => this.gotoNew()} primary={true} /> : <RaisedButton label="New Entry" primary={true} />}
</form>
onSearchClick = (value) => {
this.setState({
loading: true,
searchQuery: value,
showCourtesy: false,
}, function () {
this.doSearch();
});
}
这就是所谓的
doSearch() {
this.setState({
loading: true,
showCourtesy: false
}, function () {
});
var search_url = "http://10.0.2.31/testwebapi/api/data?"
+ "forename=" + this.state.forename
+ "&surname=" + this.state.surname
+ "&caseid=" + this.state.caseid
+ "&postcode=" + this.state.postcode
+ "&telephone=" + this.state.telephone
+ "&email=" + this.state.email
+ "&title=" + this.state.title
var _this = this;
this.serverRequest =
axios
.get(search_url
)
.then(function (res) {
_this.state.searchResults = res.data;
_this.setState({
loading: false,
})
console.log(res)
})
.catch(function (error) {
console.log(error);
window.alert("Unauthorized To Access This Please Contact IT If You Believe You Should Be")
})
}
最佳答案
要阻止表单 submit
事件重定向,您需要调用 event.preventDefault
方法。
您可以内嵌添加它,如下所示:
<form onSubmit={ e => { this.onSearchClick(this); e.preventDefault(); }}></form>
请记住上面的内容,就像您的原始代码一样,将对组件的引用传递给 onSearchClick
方法,但从您的代码来看,该方法似乎需要一个字符串。但这超出了本问题的范围。
您还可以重构 onSearchClick
方法以接受事件作为第一个参数:
onSearchClick = ( event, value ) => {
this.setState({
loading: true,
searchQuery: value,
showCourtesy: false,
}, function () {
this.doSearch();
});
event.preventDefault();
}
<form onSubmit={ this.onSearchClick.bind( this ) }></form>
同样,值
将不会被传递。我建议使用refs
来保留对查询输入字段的引用,因此值将是this.refs.query.value
。
关于javascript - ReactJs 表单按 Enter 键提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45799131/