在Reactjs中,如何为我的DataTable添加搜索过滤器?
P粉447002127
P粉447002127 2023-08-17 15:51:24
[React讨论组]
<p>我想通过在ReactJS中添加搜索过滤器来增强我的DataTable。我希望用户能够在表格中搜索特定的条目。目标是允许用户轻松搜索和查找表格中的特定数据。如何实现这个?</p> <pre class="brush:php;toolbar:false;">&lt;&gt;&lt;ScrollView showsHorizontalScrollIndicator&gt; &lt;View style={styles.root}&gt; &lt;TouchableOpacity style={[styles.button, styles.buttonOutline]} onPress={handleBackButtonClick} &gt; &lt;Text style={styles.buttonOutlineText}&gt;返回&lt;/Text&gt; &lt;/TouchableOpacity&gt; &lt;/View&gt; &lt;TextInput style={styles.searchInput} placeholder="按客户搜索..." /&gt; &lt;DataTable style={styles.container}&gt; &lt;DataTable.Header style={styles.tableHeader}&gt; &lt;DataTable.Title&gt;客户&lt;/DataTable.Title&gt; &lt;DataTable.Title&gt;地址&lt;/DataTable.Title&gt; &lt;DataTable.Title&gt;手机号码&lt;/DataTable.Title&gt; &lt;DataTable.Title&gt;车牌号码&lt;/DataTable.Title&gt; &lt;/DataTable.Header&gt; {displayedCustomers.map((customer, index) =&gt;{ return( &lt;TouchableOpacity key={index} onPress={() =&gt; handleRowClick(customer)} style={[ styles.row, selectedRow &amp;&amp; selectedRow.id === customer.id &amp;&amp; styles.selectedRow]} &gt; &lt;DataTable.Row key={index}&gt; &lt;DataTable.Cell&gt;{customer.customer}&lt;/DataTable.Cell&gt; &lt;DataTable.Cell&gt;{customer.address}&lt;/DataTable.Cell&gt; &lt;DataTable.Cell&gt;{customer.mobileno}&lt;/DataTable.Cell&gt; &lt;DataTable.Cell&gt;{customer.plateno}&lt;/DataTable.Cell&gt; &lt;/DataTable.Row&gt; &lt;/TouchableOpacity&gt; ) })} &lt;/DataTable&gt; &lt;DataTable.Pagination page={currentPage} numberOfPages={Math.ceil(customers.length / itemsPerPage)} onPageChange={handlePageChange} /&gt; &lt;/ScrollView&gt;</pre>
P粉447002127
P粉447002127

全部回复(1)
P粉637866931

创建一个状态来保存搜索查询,并创建另一个状态来存储过滤后的数据:

const [searchQuery, setSearchQuery] = useState('');
const [filteredCustomers, setFilteredCustomers] = useState(customers); // 初始化为完整列表

现在添加这个函数。首先更新searchQuery状态,然后根据给定的text参数进行过滤,并将结果设置为filteredCustomers状态。

const handleSearchInputChange = (text) => {
    setSearchQuery(text);
    const filtered = customers.filter(
      (customer) =>
        customer.customer.toLowerCase().includes(text.toLowerCase()) ||
        customer.address.toLowerCase().includes(text.toLowerCase()) ||
        customer.mobileno.includes(text) ||
        customer.plateno.includes(text)
    );
    setFilteredCustomers(filtered);
  };

每次在搜索TextInput中输入时都要执行这个逻辑。

<TextInput
   placeholder="按客户搜索..."
   onChangeText={handleSearchInputChange}
   value={searchQuery}
/>

最后,只需通过filtredCustomers而不是displayedCustomers进行映射:

{filteredCustomers.map((customer, index) => {
  return (
     <TouchableOpacity
        key={index}
     >
       // ....
     </TouchableOpacity>
  )  
})
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号