2016-09-18 52 views
1

我在顶部有一个搜索栏,结果会呈现为相当基本的Listview。我想让搜索结果(字符串)中突出显示的每个单词都输入到搜索栏中(不区分大小写)。将字符串拆分为各种文本元素

在我做一个基本的分裂的时刻:

let split = question.title.split(this.state.searchInput); 

,并渲染:

<Text style={styles.title}> 
{split[0]} 
</Text> 
    {split.length > 1 ? 
    <View style={{flexDirection: 'row'}}> 
     <Text style={styles.fatTextResult}> 
     {this.state.searchInput} 
     </Text> 
     <Text style={styles.title}> 
     {split[1]} 
     </Text> 
    </View> 
    : 
    null 
    } 

这种分裂显然不能在未在连接2个字打字时工作搜索结果。我怎么能做到这一点?

ATM它看起来像这样..

enter image description here

回答

1

试试这个:

highlightWord(word , search){ 

    var newWord = word.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,""); 

    if (search.toLowerCase().indexOf(newWord.toLowerCase()) != -1){ // if word in question 
     // highlight it 
     return <Text style={{fontWeight:'bold'}}>{word}</Text> 
    } 
    else{ 
     return <Text>{word}</Text> 
    } 
} 

renderRow(question){ 

    let split = question.title.split(' '); //divide question in words 
    textViews = []; 
    for (var i=0 ; i<split.length ; i++){ 
     var word = split[i]; // get words 
     textViews.push(highlightWord(word,this.state.searchInput)); 
    } 

    // return all words together (highlighted or not) 
    return <View style={{flexDirection:'row'}}>{ textViews }</View> 
} 

编辑

我添加的第一行上highlightWord处理与标点符号的话。

+0

感谢这个作品,但不是以标点符号结束的单词......任何想法? – dv3

+0

它应该带有标点符号的文字。 – leo7r