在JSX中用标记替换部分字符串

时间:2015-05-27 06:16:03

标签: reactjs react-jsx

我试图用JSX标签替换部分字符串,如下所示:

render: function() {
    result = this.props.text.replace(":",<div className="spacer"></div>);
    return (
         <div>        
             {result}
         <div>        
    );
}

但鉴于this.props.textLorem : ipsum,结果为

<div>
    Lorem [object Object] ipsum.
</div>

有没有办法解决这个或另一种用JSX标签替换字符串部分的方法?

13 个答案:

答案 0 :(得分:18)

当您将JSX元素作为第二个参数传递给replace()时,该元素将转换为字符串,因为replace()需要将字符串作为第二个参数。您需要做的是将字符串转换为字符串数组和JSX元素。因此,您的result变量应包含['Lorem ', <div className="spacer"></div>, ' ipsum']

之类的内容

这样的事情:

function flatMap(array, fn) {
  var result = [];
  for (var i = 0; i < array.length; i++) {
    var mapping = fn(array[i]);
    result = result.concat(mapping);
  }
  return result;
}

var Comp = React.createClass({
  render: function () {
    var result = 'Lorem : ipsum';
    result = flatMap(result.split(':'), function (part) {
      return [part, <div>spacer</div>];
    });
    // Remove the last spacer
    result.pop();
    return (
      <div>        
        {result}
      </div>
    );
  }
});

答案 1 :(得分:5)

以下也应该有效(假设是ES6),唯一的细微差别是文本实际上是在DIV元素中包装而不是在它之前,假设你要使用CSS来实际间距,这不应该是#t; t是个问题。

NSError *error; NSDictionary *dict=@{ @"allgroups": @{ @"groupname": @"prasad", @"group_id":@"26", @"user_id":@"8", @"contacts": @[contactsArray] } }; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error]; NSString *saveString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSString *myRequestString = [NSString stringWithFormat:@"%@",saveString]; NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithFormat:@"http://example.php"]]]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; [request setHTTPMethod: @"POST"]; //post section [request setHTTPBody: myRequestData]; NSURLResponse *response; NSError *err; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil]; NSLog(@"String value is:: %@",returnString);

答案 2 :(得分:3)

接受的答案是两岁。对于此问题,创建了#3368问题,并根据工作在React上的Facebook员工提供的解决方案,创建了react-string-replace

使用react-string-replace,以下是解决问题的方法

const reactStringReplace = require('react-string-replace');

const HighlightNumbers = React.createClass({
  render() {
    const content = 'Hey my number is 555:555:5555.';
    return (
      <span>
        {reactStringReplace(content, ':', (match, i) => (
          <div className="spacer"></div>
        ))}
      </span>
    );
  },
});

答案 3 :(得分:3)

你们正在使用复杂的方法,只需保持简单即可:

function replaceJSX(str, find, replace) {
    let parts = str.split(find);
    for(let i = 0, result = []; i < parts.length; i++) {
        result.push(parts[i]);
        result.push(replace);
    }
    return (
        <>{result}</>
    );
}

用法

replaceJSX(variable, ":", <br />);

答案 4 :(得分:1)

我有更常见的任务 - 用自定义标签包装所有(英语)单词。 我的解决方案:

class WrapWords extends React.Component {
  render() {
    const text = this.props.text;
    const isEnglishWord = /\b([-'a-z]+)\b/ig;
    const CustomWordTag = 'word';

    const byWords = text.split(isEnglishWord);

    return (
    <div>
      {
        byWords.map(word => {
          if (word.match(isEnglishWord)) {
            return <CustomWordTag>{word}</CustomWordTag>;
          }
          return word;
        })
      }
    </div>
    );
    
  }
}

// Render it
ReactDOM.render(
  <WrapWords text="Argentina, were playing: England in the quarter-finals (the 1986 World Cup in Mexico). In the 52nd minute the Argentinian captain, Diego Maradona, scored a goal." />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="react"></div>

答案 5 :(得分:0)

如果您还希望能够在替换内进行替换(例如,突出显示网址中的搜索字词),请查看我创建的此节点模块 - https://github.com/marcellosachs/react-string-replace-recursively

答案 6 :(得分:0)

经过一番研究后,我发现现有的图书馆并不符合我的要求。所以,当然,我写了自己的:

https://github.com/EfogDev/react-process-string

它非常易于使用。你的案例:

let result = processString({
    regex: /:/gim,
    fn: () => <div className="spacer"></div>
})(this.props.test);

答案 7 :(得分:0)

带有钩子的示例:

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] = (
        <span className='highlight' key={i}>
          {parts[i]}
        </span>
      )
    }
    return <div>{parts}</div>
  }

  useEffect(() => {
    //skip first run
    if (isFirstRun.current) {
      isFirstRun.current = false
      return
    }
    resultSet(wrap())
  }, [value, highlightText])

  return result
}

答案 8 :(得分:0)

为jsx写了一个实用程序功能。

const wrapTags = (text: string, regex: RegExp, className?: string) => {
  const textArray = text.split(regex);
  return textArray.map(str => {
    if (regex.test(str)) {
      return <span className={className}>{str}</span>;
    }
    return str;
  });
};

答案 9 :(得分:0)

我已经开始遵循以下简单的解决方案,其中不包括第三方库或正则表达式,也许它仍然可以帮助某人。

主要只是使用.replace()将字符串替换为以字符串形式编写的常规html,例如:

text.replace('string-to-replace', '<span class="something"></span>')

然后在元素内使用dangerouslySetInnerHTML进行渲染。

完整示例:

const textToRepace = 'Insert :' // we will replace : with div spacer
const content = textToRepace.replace(':', '<div class="spacer"></div>') : ''

// then in rendering just use dangerouslySetInnerHTML
render() {
    return(
        <div dangerouslySetInnerHTML={{
            __html: content
        }} />
    )
}

答案 10 :(得分:0)

我认为这是最轻巧的完美解决方案:

render() {
    const searchValue = "an";
    const searchWordRegex = new RegExp(searchValue, "gi");
    const text =
      "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text";
    return (
      <div>
        {text.split(searchWordRegex).length > 1
          ? text.split(searchWordRegex).map((chunk, index) => {
              if (chunk !== "") {
                return index === 0 &&
                  ! new RegExp("^" + searchValue, "gi").test(text) ? (
                  chunk
                ) : (
                  <span key={index}>
                    <span
                      className="highlight"
                      style={{
                        fontWeight: "bold"
                      }}
                    >
                      {searchValue.charAt(0).toUpperCase() +
                        searchValue.slice(1)}
                    </span>
                    {chunk}
                  </span>
                );
              } else {
                return null;
              }
            })
          : text}
      </div>
    );
  }

这是工作中的example

答案 11 :(得分:0)

WEB全球范围内没有任何东西可以解决这个问题-https://www.npmjs.com/package/regexify-string

使用React,字符串并且没有任何其他依赖项

ui.miRNA <- fluidPage(
  selectInput("MicroRNA", "miRNA", choices = unique(data_prep.miRNA$miRNA)),

  plotOutput("myplot"))

server <- function(input, output, session) {
  
  data_selected <- reactive({
    filter(data_prep.miRNA, miRNA %in% input$MicroRNA)
  })
  
  output$myplot <- renderPlot({
      fitSurv <-   survfit(Surv(TimeDiff, Status) ~ cut(value, quantile(value, probs = c(0, .4, .8)), include.lowest=TRUE),data = data_selected())

    ggsurvplot(fitSurv)
    
    
  })
}

shinyApp(ui.miRNA, server)

答案 12 :(得分:0)

像这样:

function replaceByComponent(string, component) {
  const variable = string.substring(
    string.lastIndexOf("{{") + 2, 
    string.lastIndexOf("}}")
  );
  const strParts = string.split(`{{${variable}}}`);
  const strComponent = strParts.map((strPart, index) => {
    if(index === strParts.length - 1) {
      return strPart
    }
    return (   
      <>
        {strPart}
        <span>
          {component}
        </span>
      </>
    )
  })
  return strComponent
}