Replace part of string with tag in JSX

前端 未结 12 1293
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 10:11

    When you pass a JSX element to replace() as the second argument, that element is converted to a string because replace() expects a string as a second argument. What you need to do is convert your string to an array of strings and JSX elements. So your result variable should contain something like ['Lorem ',

    , ' ipsum'].

    Something like this:

    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, 
    spacer
    ]; }); // Remove the last spacer result.pop(); return (
    {result}
    ); } });

提交回复
热议问题