Replace part of string with tag in JSX

前端 未结 12 1310
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 09:39

I\'m trying to replace parts of a string with JSX tags, like so:

render: function() {
    result = this.props.text.replace(\":\",
12条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 09:58

    Example with hooks:

    import React, { useEffect, useState, useRef } from 'react'
    
    export function Highlight({ value, highlightText }) {
      const [result, resultSet] = useState(wrap())
    
      const isFirstRun = useRef(true) 
    
      function wrap() {
        let reg = new RegExp('(' + highlightText + ')', 'gi')
        let parts = value.split(reg)
    
        for (let i = 1; i < parts.length; i += 2) {
          parts[i] = (
            
              {parts[i]}
            
          )
        }
        return 
    {parts}
    } useEffect(() => { //skip first run if (isFirstRun.current) { isFirstRun.current = false return } resultSet(wrap()) }, [value, highlightText]) return result }

提交回复
热议问题