reactjs - 单击过滤器按钮后,我想清除文本字段
问题描述
在这段代码中,我无法清除两个文本字段,即使我在通过this.Search
函数单击过滤器后将它们的状态设置为空白。
import React from 'react' import Axios from './Axios' import
'./index.css' export default class Practise extends React.Component {
constructor(props) {
super(props)
this.state = {
lists: [],
names: '',
emails: '',
arr: [],
}
this.Search = (names, emails) => {
const arr = this.state.lists.filter(item => {
if (item.name.includes(this.state.names) && item.email.includes(this.state.emails)) {
return true
} else {
return false
}
})
this.setState({names:''})
this.setState({emails:''})
console.log(arr)
}
}
componentDidMount() {
Axios.get('/comments').then(response => {
// console.log(response.data, 'data')
this.setState({ lists: response.data })
}).catch(response => {
console.log(response, 'Errored!!!')
this.setState({ errored: 'Error has Occured' })
})
}
render() {
const { lists, arr, names, emails } = this.state
return (
<>
<div >
<input type='text' onChange={(e) => this.setState({ names: e.target.value })} />
<input type='text' onChange={(p) => this.setState({ emails: p.target.value })} />
<button onClick={()=>this.Search()}>Filter</button>
</div>
<div>
{lists.length ? lists.map(item =>
<div className='divone' key={item.id}>
Id:- {item.id} <br />
Name:- {item.name} <br />
Email:- {item.email}</div>) : null}
</div>
</>
)
}
};
解决方案
您必须将 value 属性添加到两个输入。之后,如果将状态更改为空白字符串,输入的值也将变为空白。这是一个示例 -
<input type='text' value={this.state.names} onChange={(e) => this.setState({ names: e.target.value })} />
<input type='text' value={this.state.emails} onChange={(p) => this.setState({ emails: p.target.value })} />
它应该工作。
推荐阅读
- import - 在第 4 行声明标题
- python - Tkinter GUI 无法启动 - 线程 - Tkinter 对象没有属性“标签”
- javascript - 如何在 JavaScript 中定义的 x、y 坐标处模拟点击?
- r - ggplot:为什么 scale_x_date 需要 date_labels 中的附加元素?
- python - 如何在python中使用Ctypes最小化窗口
- java - 为什么 spring-cloud-starter-config 忽略 bootstrap.properties?
- java - 尽管 ListView 和 SimpleAdapter 有数据,Android ListView 不显示项目
- c++ - 如何在 C++ 中将二维数组转换为一维?
- git - 我在哪里可以获得/生成要在詹金斯中使用的 git 项目的凭据 ID?
- android - 将图像加载到cardview中的imageButton会在cardview中留下空白