【发布时间】:2018-03-14 08:22:36
【问题描述】:
我遇到了一个相当愚蠢的问题。我正在创建我的第一个 React 应用程序,我遇到了一个小问题,在我提交表单后我无法清除我的输入值。尝试谷歌搜索这个问题,在这里找到了一些类似的线程,但我无法解决这个问题。我不想更改组件/应用程序的状态,只是将输入的值更改为空字符串。我尝试清除 onHandleSubmit() 函数中的输入值,但出现错误:
“无法设置未定义的属性‘值’”。
我的搜索栏组件:
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;
【问题讨论】:
-
感谢大家的 cmets !愚蠢的我……它奏效了。我想如果我改变状态,我的数据就会从屏幕上消失(是的,这就是我的逻辑有多糟糕)。谢谢!
标签: javascript forms reactjs input submit