2016-01-09 28 views
0

我有,例如一个句子:阵营本地替换字符串的部分与标签元素

我“怎么现在褐牛”

想找到句子中的某些词,例如“现在”和“牛“,并让它们在每个单词周围添加不​​同的标签。例如:

<Text style={styles.text}> 
How <TouchableHighlight><Text>now</Text></TouchableHighlight>brown<TouchableHighlight><Text>cow</Text></TouchableHighlight> 

但我不能看到如何将这些元素标记添加到他们。基本的代码如下:

render() { 
    return (
    var sentence = "How now brown cow"; 
    <TouchableHighlight onPress={() => this._pressRow(rowID)}> 
    <View> 
     <View style={styles.row}> 
     <Text style={styles.text}> 
     {sentence} 
     </Text> 
     </View> 
    </View> 
    </TouchableHighlight> 
); 
}, 
+0

没有我的回答解决你的问题? – purii

回答

1
  • 使用String.prototype.split()迭代通过阵列分割你的句子。
  • 请确保您将flexDirection更改为row,否则单个元素将位于单行中。
  • 我在每个单词之后加了一个空间,也许你可以寻找更好的解决方案,以便空间不会被添加到最后一个元素。

    render() { 
        const sentence = "How now brown cow"; 
        const words = sentence.split(' '); 
        const wordsToHighlight = ['now', 'cow']; 
    
        const renderWord = (word, index) => { 
        if(wordsToHighlight.indexOf(word) > -1) return (<TouchableHighlight><Text>{word} </Text></TouchableHighlight>); 
        return (<Text>{word} </Text>); 
        } 
    
        return (<View style={{flexDirection: 'row'}}>{React.Children.map(words, renderWord)}</View>); 
    }