当前位置: 动力学知识库 > 问答 > 编程问答 >

reactjs - Replace part of string with tag in JSX

问题描述:

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

render: function() {

result = this.props.text.replace(":",<div className="spacer"></div>);

return (

<div>

{result}

<div>

);

}

But given that this.props.text is Lorem : ipsum, it results in

<div>

Lorem [object Object] ipsum.

</div>

Is there a way to solve this or another way to replace parts of a string with JSX tags?

网友答案:

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 ', <div className="spacer"></div>, ' 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, <div>spacer</div>];
    });
    // Remove the last spacer
    result.pop();
    return (
      <div>        
        {result}
      </div>
    );
  }
});
网友答案:

The following should also work (assumes ES6), The only nuance is that the text is actually wrapped inside a DIV element and not preceded by it, assuming you are going to use CSS for the actual spacing this shouldn't be a problem.

const result = this.props.text.split(':').map(t => { return <div className='textItem'>{t}</div>; });

网友答案:

If you'd also like to be able to make replacements within replacements (for example, to highlight search terms within urls), check out this node module I created - https://github.com/marcellosachs/react-string-replace-recursively

网友答案:

I had the more common task - wrap all (English) words by custom tag. My solution:

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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: