Javascript 如何在字符串中插入span并将其作为HTML打印在react应用程序中
我有这段代码,它可以获取一个字符串和一些变量,并将变量注入字符串中。这是我的应用程序中需要的,因为文本通常来自CMS,并且必须是可编辑的。有时字符串的可变部分是彩色的或是不同的字体,所以我试图制作它,以便在必要时可以将其包装起来。但我的react应用程序将所有内容都作为字符串发布Javascript 如何在字符串中插入span并将其作为HTML打印在react应用程序中,javascript,html,reactjs,text-to-html,Javascript,Html,Reactjs,Text To Html,我有这段代码,它可以获取一个字符串和一些变量,并将变量注入字符串中。这是我的应用程序中需要的,因为文本通常来自CMS,并且必须是可编辑的。有时字符串的可变部分是彩色的或是不同的字体,所以我试图制作它,以便在必要时可以将其包装起来。但我的react应用程序将所有内容都作为字符串发布 var VariableInjection = (stringToEdit, variablesToInject) => { const matches = stringToEdit.match(/{[
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(“这是{varA},这是{varB},{varA:1,varB:{value:2,class:“test class”})
给出:
'this is the 1 and this is the <span class="test Class">2</span>'
“这是1,这是2”
听起来您需要在呈现文本的组件上使用。正如名称所示,这不一定是最好的解决方案(谨慎使用),但它应该可以解决代码工作方式的问题
编辑:
render:function(){
返回;
}
'this is the 1 and this is the <span class="test Class">2</span>'
render: function() {
return <div dangerouslySetInnerHTML={{ __html: html }}></div>;
}