我遇到了一个相当愚蠢的问题。我正在创建我的第一个 React 应用程序,并且遇到了一个小问题,在提交表单后我无法清除我的输入值。尝试用谷歌搜索这个问题,在这里找到了一些类似的线程,但我无法解决这个问题。我不想更改组件/应用程序的状态,只是将输入的值更改为空字符串。我尝试清除 onHandleSubmit()
函数中的输入值,但出现错误:
"Cannot set property 'value' of undefined".
我的搜索栏组件:
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;
最佳答案
您有一个受控组件,其中输入
值由this.state.city
确定。因此,一旦您提交,您必须清除您的状态,这将自动清除您的输入。
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
关于javascript - React - 表单提交后清除输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46539480/