美文网首页
ReactNative 搜索词高亮 split替换

ReactNative 搜索词高亮 split替换

作者: 焦糖大瓜子 | 来源:发表于2021-06-17 10:03 被阅读0次
interface HighLightProps {
  str: string,
  keywords: string,
  style: TextStyle
}
const HighLightKeywords: FC<HighLightProps> = ({ str = '', keywords = '', style }) => {
  if (!str) return null
  const newData = str.split(keywords) //  通过关键字的位置开始截取,结果为一个数组
  return (
    <Text style={style}>
      {
        newData.map((item, index) => {
          if (!index) { // 当下标是0的时候,直接返回当前项
            return <Text key={index}>{item}</Text>
          } else {
            return <Text key={index}><Text style={{ color: '#f00' }}>{keywords}</Text>{item}</Text>
          }
        })
      }
    </Text>
  )
}

使用

// usage
  <HighLightKeywords str='关键词高亮' style={{ fontSize: 16, height: 24, lineHeight: 24 }} keywords={’关键词高亮‘} />

相关文章

网友评论

      本文标题:ReactNative 搜索词高亮 split替换

      本文链接:https://www.haomeiwen.com/subject/fynqyltx.html