2017-05-11 12 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"})給出:

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

回答

1

這聽起來像你需要呈現的文本組件上使用dangerouslysetinnerhtml。顧名思義,這不一定是最好的解決方案(謹慎使用),但它應該可以解決代碼工作的問題。

編輯:JSFiddle

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