Как выделить результаты поиска в React-Native FlatList? - PullRequest
0 голосов
/ 28 февраля 2019

Я новичок в React-native.Мне нужно выделить результаты поиска в моем FlatList, пока я печатаю в строке поиска.Есть 2 компонента: response-native-highlight-words и реагировать-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 голосов
/ 05 марта 2019

Вы можете передать текст или пользовательский вид в ListItem компонент как props для 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 }}
/>
0 голосов
/ 05 марта 2019
 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 () вашего поля поиска.

0 голосов
/ 28 февраля 2019

Вы можете выделить свои собственные стили.

Вот простой пример:

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 />.

...