2017-05-11 5 views
1

私はこのコードを持っています。これは文字列といくつかの変数をとり、変数を文字列に注入することができます。テキストはしばしばCMSから来て、編集可能でなければならないので、これは私のアプリでは必要です。時には、文字列の可変部分が色付けされているか、別のフォントになっているので、必要に応じてそれをラップすることができるようにしようとしていました。しかし、私の反応アプリはすべてをストリングとして投稿します。どのように文字列にスパンを挿入し、それを私の反応アプリにHTMLとして出力させることができます

var VariableInjection = (stringToEdit, variablesToInject) => { 
    const matches = stringToEdit.match(/{[a-z][A-z]*}/g); 
    const strippedMatches = matches.map(m => m.replace('{', '')).map(m => m.replace('}', '')); 

    for (let i = 0; i < matches.length; i += 1) { 
     const replaceWith = variablesToInject[strippedMatches[i]]; 
     if (typeof replaceWith === 'string' || typeof replaceWith === 'number') { 
      stringToEdit = stringToEdit.replace(matches[i], replaceWith); 
     } else { 
      stringToEdit = stringToEdit.replace(matches[i], `<span class="${replaceWith.class}">${replaceWith.value}</span>`); 
     } 
    } 

    return stringToEdit; 
}; 

VariableInjection("this is the {varA} and this is the {varB}", { varA: 1, varB: 2})ができます:

'this is the 1 and this is the 2' 

VariableInjection("this is the {varA} and this is the {varB}", { varA: 1, varB: { value:2, class:"test Class"})ができます:あなたはテキストをレンダリングするコンポーネント上dangerouslysetinnerhtmlを使用する必要がありますように

'this is the 1 and this is the <span class="test Class">2</span>' 

答えて

1

ですね。名前が示すように、これは必ずしも最適な解決策ではありませんが(注意して使用する必要はありませんが、コードの仕組みの問題を解決するはずです)。

編集:JSFiddle

render: function() { 
    return <div dangerouslySetInnerHTML={{ __html: html }}></div>; 
    } 
関連する問題