Mam aplikację internetową Reactjs, w której muszę pokazywać określony kolor tylko wybranym zdaniom. Mam dwa stany, które przechowują tablice zdań, które są twarde i bardzo trudne, które otrzymujemy dynamicznie z interfejsu API. Muszę pokolorować tylko trudne i bardzo trudne zdania odpowiednio na żółto i czerwono, a resztę tekstu w domyślnym kolorze.
Przypuśćmy, że to jest pełny tekst
It's the possibility of having a dream come true that makes life interesting. He stepped down, trying not to look long at her, as if she were the sun, yet he saw her, like the sun, even without looking. I cannot fix on the hour, or the spot, or the look or the words, which laid the foundation. Satan trembles when he sees the weakest saint upon their knees
Następnie api skanuje zdanie i wysyła twarde i bardzo trudne zdanie z powyższego akapitu
{
"hard": [
"It's the possibility of having a dream come true that makes life interesting",
"I cannot fix on the hour, or the spot, or the look or the words, which laid the foundation.",
]
"very_hard": [
“He stepped down, trying not to look long at her, as if she were the sun, yet he saw her, like the sun, even
without looking.”
]
}
To jest kod:
states={
hardArray: [],
vhardArray: []
};
{enteredText.split(". ").map(word => {
if (this.state.vhardArray.includes(word)) {
return <span className="vhardColor">{word}</span>;
}
if (this.state.hardArray.includes(word)) {
return <span className="hardColor">{word}</span>;
}
return [word, ". "];
})}
Jednak gdy sprawdzamy elementy DOM, nie ma tagu span wokół trudnych i bardzo trudnych zdań, więc najprawdopodobniej css nie został do nich przypisany. Jak poprawnie przypisać css?
2 odpowiedzi
Zamiast używać podziału, zalecę użycie zamiany i wyrażenia regularnego. jest bardziej elastyczny i trwały. Musisz raz zapętlić.
Można to uprościć, jak na poniższym przykładzie, można użyć do usuwania JSX „”. Leniwy w konfiguracji react project lub stackbliz
const vtext = [":D", ";)"]
const htext = [":>"]
const compileEmoji = (emj) => {
if(vtext.indexOf(emj) > -1) return '<span class="vtext">{emj}</span>'
if(htext.indexOf(emj) > -1) return '<span class="htext">{emj}</span>'
return emj
}
const buildEmoji = (text = "") => {
return text.replace(/(\S+)(\s+)/g, function(w, mat1, mat2) {
return `${compileEmoji(mat1)}${mat2}`
})
}
console.log(buildEmoji("This is something :> new :D hu hahaha ;) "))
Możesz dynamicznie dodawać css do dokumentu na przykład:
let vhardColor = document.createElement('style');
vhardColor.innerHTML = `
.vhardColor {
color: blue;
} `;
document.head.appendChild(vhardColor);