我想提交我的表單,當輸入鍵被按下,但如果我使用onSubmit={() => this.onSearchClick(this)}
這是我的功能,我需要運行所有它它把表單放入我不想要的網址發生所有我需要做的就是讓它運行該函數,這將執行一個API調用。ReactJs表單提交輸入鍵按
我的代碼是這樣的
<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")
})
}
您需要在提交偵聽器中放置'event.preventDefault()',並將該事件對象作爲參數傳遞。 'onSubmit = {e => {this.onSearchClick(this); e.preventDefault(); }}' – pawel
@pawel我把它放在輸入或表單上? –
@andywilson'onSubmit'監聽器進入'form'。 – pawel