【问题标题】:How to highlight search results in React-Native FlatList?如何在 React-Native FlatList 中突出显示搜索结果?
【发布时间】:2019-02-28 14:41:12
【问题描述】:

我是 React-native 的新手。在搜索栏中键入内容时,我需要在我的 FlatList 中突出显示搜索结果。有 2 个组件:react-native-highlight-wordsreact-native-text-highlight,但我不知道如何使用它们! 这是我的代码:

import React, { Component } from 'react';
import {StyleSheet, Text, View, FlatList, TouchableOpacity } from 'react-native';
import { List, ListItem, SearchBar } from 'react-native-elements';
import DropdownMenu from 'react-native-dropdown-menu';
import {Header, Left, Right, Icon} from 'native-base'

var SQLite = require('react-native-sqlite-storage')
var db = SQLite.openDatabase({name: 'test.sqlite', createFromLocation: '~dictionary.sqlite'})
var data = [["English", "Arabic", "Persian"]];

export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {record: [], arrayholder : [], query:''};
    db.transaction((tx) => {
      tx.executeSql('SELECT * FROM tblWord', [], (tx, results) => {
          let row = results.rows.item();
          arrayholder = results.rows.raw()
          record = results.rows.raw()
          this.setState({arrayholder: arrayholder})
          this.setState({ record: record })
          }});});  
      }

  searchFilterFunction = text => {
    var newData = this.state.arrayholder;
    newData = this.state.arrayholder.filter(item => {
      const itemData = item.word_english.toLowerCase()
      const textData = text.toLowerCase()
      return itemData.indexOf(textData) > -1 });
    this.setState({query: text,record: newData });
  };


  render() {
    return (
      <View style = {styles.container}>
        <Header style={styles.headerStyle}>
            ...
        </Header>
        <View style={styles.menuView}>
          <DropdownMenu
            bgColor={"#B38687"}
            activityTintColor={'green'}
            titleStyle={{color: '#333333'}} 
            handler={(selection, row) => this.setState({text4: data[selection][row]})}
            data={data}
            >
          </DropdownMenu>
        </View >
        <View >
          <View style={styles.searchBarView}>
            <SearchBar
              placeholder="Search"
              lightTheme
              value = {this.state.query}
              onChangeText={text => this.searchFilterFunction(text)}
              autoCorrect={false}
              inputStyle={{backgroundColor: 'white'}}
              containerStyle={{backgroundColor: 'white', borderWidth: 1, borderColor:'#B38687', }}
              />
          </View>

          <View style={styles.flatListVew}>
            <List containerStyle={{ flexDirection: 'column-reverse', borderTopWidth: 0, borderBottomWidth: 0 }} >
              <FlatList 
                data={this.state.record} 
                keyExtractor={((item, index) => "itemNo-" + index)}
                renderItem={({item}) => (
                  <ListItem
                    roundAvatar
                    onPress={() => {this.props.navigation.navigate('Screen2', {data: (item.word_english +'\n' + item.word_arabic)} ); }}
                    title={item.word_english}
                    containerStyle={{ borderBottomWidth: 0 }}
                  /> )}
                />
              </List>
            </View>
          </View>
       </View>);}
          }

const styles = StyleSheet.create({
 ...

我希望结果如下所示:

任何帮助将不胜感激。

【问题讨论】:

  • @simaAttar-ListItem 组件的共享代码。
  • @Rocky 我编辑了我的问题并包含了我的整个代码。

标签: react-native react-native-flatlist searchbar


【解决方案1】:

您可以将文本或自定义视图作为props 传递给ListItem 组件title。正如您所说,我正在使用React Native Highlight Words 突出显示文本。

通过添加以下行添加React Native Highlight Words

import Highlighter from 'react-native-highlight-words';

更新ListItem 组件的代码以获得所需的结果:

<ListItem
    roundAvatar
    onPress={() => {this.props.navigation.navigate('Screen2', {data: (item.word_english +'\n' + item.word_arabic)} ); }}
    title={
      <Highlighter
          highlightStyle={{backgroundColor: 'yellow'}}
          searchWords={[this.state.query]}
          textToHighlight={item.word_english}
      />}
    containerStyle={{ borderBottomWidth: 0 }}
/>

【讨论】:

    【解决方案2】:

    您可以使用自己的样式突出显示。

    这是一个简单的例子:

    const myList = [{ text: 'Hi', id: 1 }, ... ]
    
    class List extends Component {
      this.state = { highlightedId: undefined }
    
      render() {
        return (
            <FlatList
            data={myList}
            renderItem={({item}) => <Text style={item.id === this.state.highlightedId ? styles.hightlighted : undefined}>{item.text}</Text>}
          />
        )
      }
    }
    
    const styles = StyleSheet.create({
      highlighted: {
        backgroundColor: "yellow"
      }
    })
    

    在您的情况下,您可以调整&lt;ListItem /&gt;containerStyle

    【讨论】:

    • 嗯..谢谢@J。海丝特。让我看看我能做什么:|
    • @simaAttar 如果您做不到,请告诉我,我可以为您提供更多帮助。
    • 其实我不明白如何在我的代码上实现你的代码,仅供参考,这是一个字典应用程序,它将在 flatList 中搜索单词,所以如果你仍然认为你的代码是合适的,请解释更多。非常感谢
    • 我看不到足够的代码。此外,代码的格式也难以阅读。
    【解决方案3】:
     handleChangeText = param => {
    const {categoryList} = this.state;
    const regEx = "\\s*(" + param + ")\\s*"
    const validator = new RegExp(regEx, 'i');
    let filterData = [];
    //here is categorylist is the data supplied to flatlist.
    categoryList.forEach(item => {
      let flag = validator.test(item.teamtype);
      if (flag) {
        //here set the highlighting color
      }
    })
    

    };

    调用搜索字段的上述函数 onChangeText()。

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 2014-07-25
      • 2018-03-23
      • 1970-01-01
      • 2021-07-24
      • 2017-11-02
      • 1970-01-01
      • 2019-11-26
      相关资源
      最近更新 更多