首页 > 解决方案 > 单击过滤器按钮后,我想清除文本字段

问题描述

在这段代码中,我无法清除两个文本字段,即使我在通过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>
               </>
           )
       }
   
   };

标签: reactjs

解决方案


您必须将 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 })} />

它应该工作。


推荐阅读