如何在React-Native FlatList中突出显示搜索结果?

时间:2019-02-28 14:41:13

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

我是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({
 ...

我希望结果看起来像这样:

enter image description here

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

您可以将文本或自定义视图作为ListItemprops传递到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 }}
/>

答案 1 :(得分:0)

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

这是一个简单的例子:

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

根据您的情况,您可以调整containerStyle中的<ListItem />

答案 2 :(得分:0)

 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()上调用上述函数。