Replace part of string with tag in JSX

前端 未结 12 1250
被撕碎了的回忆
被撕碎了的回忆 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 10:21

    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 (
        
    { byWords.map(word => { if (word.match(isEnglishWord)) { return {word}; } return word; }) }
    ); } } // Render it ReactDOM.render( , document.getElementById("react") );
    
    
    
    

提交回复
热议问题