首页 > 解决方案 > FlatList 中的 NumberOfLines - React Native

问题描述

我有一个带有简单 FlatList 和 TextInput 的本机应用程序。当我搜索任何文本时,它会在列表中突出显示,如下所示:

现在我设置“numberOfLines = 3”(根据我们的要求),现在看起来像这样:

要求是它看起来像下面这样。(请不要介意我的 WhatsApp 截图)它在这 3 行中用“...”显示突出显示的文本。

在此处输入图像描述

我正在使用以下代码显示数据

<Text numberOfLines={3} style={[subTitle,{fontSize:normalizeFontSize(14),lineHeight:normalizeLineHeight(14)}]}>

{getHighlightedText(alert)}

</Text>

高亮功能:

getHighlightedText = text => {
    //search text user inputs
    const {value} = this.props;
    if (value == "" || value == null || value == 0) {
        return <Text> {text} </Text>
    } else {
        // split the search value
        const words = value.split(/\s+/g).filter(word => word.length);
        // join if search value has more than 1 word
        const pattern = words.join('|');
        const re = new RegExp(pattern, 'gi')
        const children = [];

        let before, highlighted, match, pos = 0;
        // match using RegExp with my text
        const matches = text.match(re);

        if (matches != null) {
            // loop all the matches
            for (match of matches) {
                match = re.exec(text)
                if (pos < match.index) {
                    // before has all the text before the word that has to highlighted
                    before = text.substring(pos, match.index);
                    if (before.length) {
                        children.push(before)
                    }
                }
                highlighted = <Text style={{backgroundColor: 'coral'}}>{match[0]} </Text>
                // text is highlighted
                children.push(highlighted);

                pos = match.index + match[0].length;
            }
        }
        if (pos < text.length) {
            // text after the highlighted part
            const last = text.substring(pos);
            children.push(last);
        }
        // children array will have the entire text
        return <Text>{children} </Text>
    }
}

在这方面需要 React Native 大师的帮助。请善待我是 React Native 的新手 :)

标签: javascriptreactjsreact-nativesearchreact-native-flatlist

解决方案


React Native在嵌套对象中有<Text>一个已知问题。numberOfLines<Text>

这可能是导致您的问题的原因:)


推荐阅读