【发布时间】:2019-09-19 22:04:03
【问题描述】:
我有一个输入字段,旁边有一个“关闭 (x)”图标。当输入字段中的值发生变化时,我正在处理状态,一旦用户点击 Enter 我清除状态中的值。但是,在重新渲染之后(由于状态变化),先前的输入仍然保留在输入字段中。
constructor(props) {
super(props);
this.state = {
filterSearchQuery: null, filterSearch: null}
this.handleSearchInput = this.handleSearchInput.bind(this);
this.handleSearchReset = this.handleSearchReset.bind(this);
}
handleSearchInput(e) {
// e.preventDefault();
let val = e.target.value;
if (e.keyCode == 13)
this.setState({ entries: [], filterSearchQuery: null, filterSearch: val, pageIndex: 0, hasMore: false }, this.loadEntries);
else
this.setState({ filterSearchQuery: val });
}
handleSearchReset(e) {
//e.preventDefault();
this.setState({ entries: [], pageIndex: 0, hasMore: false, filterSearchQuery: null, filterSearch: null }, this.loadEntries);
}
渲染并返回:
<input type="text" className="outline-none flex-fill pt-0_2em pb-0_2em border-white border-none bg-color-white color-black font-12px font-weight-bold opacity-0_9" value={this.state.filterSearchQuery} placeholder="Search in results." onKeyUp={(e) => this.handleSearchInput(e)} onChange={(e) => this.handleSearchInput(e)} autoFocus={true} />
{
(this.state.filterSearchQuery && this.state.filterSearchQuery.length > 0) &&
<div className="">
<button type="button" className="close" aria-label="Close" onClick={this.handleSearchReset}>
<span aria-hidden="true">×</span>
</button>
</div>
}
handleSearchReset 函数按预期工作并设置状态。 filterSearch 和 filterSearchQuery 值都设置正确。但是,在重新渲染后,filterSearchQuery 值仍然在输入字段中可见。我该如何克服这个或我错过了什么?
提前致谢。
【问题讨论】:
标签: javascript reactjs input