单击过滤器按钮后,我想清除文本字段

时间:2021-05-03 05:21:37

标签: 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>
               </>
           )
       }
   
   };

1 个答案:

答案 0 :(得分:0)

您必须将 value prop 添加到两个输入中。之后, 如果将状态更改为空字符串,则输入的值也将变为空白。这是一个示例 -

<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 })} />

它应该可以工作。

相关问题