1

我有这段代码,它可以接受一个字符串和一些变量并将变量注入到字符串中。这在我的应用程序中是必需的,因为文本通常来自 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>'
4

1 回答 1

1

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

编辑:JSFiddle

  render: function() {
    return <div dangerouslySetInnerHTML={{ __html: html }}></div>;
  }
于 2017-05-11T12:39:45.393 回答