如何将span注入字符串并将其作为HTML打印在我的反应应用程序中

时间:2017-05-11 12:26:29

标签: javascript html reactjs text-to-html

我有这个代码,可以接受字符串和一些变量并将变量注入字符串。这在我的应用中是必需的,因为文本通常来自CMS并且必须是可编辑的。有时字符串的可变部分是彩色的或不同的字体,所以我试图使它成为可以在必要时包装它。但我的反应应用程序将所有内容都作为字符串发布。

 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"})给出:

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

1 个答案:

答案 0 :(得分:1)

听起来您需要在呈现文本的组件上使用dangerouslysetinnerhtml。这并不一定是最好的解决方案(谨慎使用),顾名思义,但它应该解决代码工作方式的问题。

修改:JSFiddle

  render: function() {
    return <div dangerouslySetInnerHTML={{ __html: html }}></div>;
  }