如何在React中为单词中的不同字母添加不同颜色?

huangapple go评论86阅读模式
英文:

How to add different colors to different letters in a word in React?

问题

如何为单词中的每个字母添加特定的颜色,如果字母重复,则每个字母的颜色应该相同。比如如果b重复出现,那么所有的b字母都应该具有相同的颜色。

这里是我的颜色对象,以键值对的形式:

const colorObj = 
{
  a: "red",
  b: "green",
  c: "blue",
  d: "violet",
  e: "yellow",
  f: "orange",
  g: "brown",
  h: "indigo",
  i: "cadetblue",
  j: "chocolate",
  k: "crimson",
  l: "darkcyan",
  m: "darkgrey",
  n: "darkolivegreen",
  o: "darkorange",
  p: "darkviolet",
  q: "deeppink",
  r: "fuchsia",
  s: "gold",
  t: "greenyellow",
  u: "khaki",
  v: "springgreen",
  w: "yellowgreen",
  x: "sienna",
  y: "royalblue",
  z: "peachpuff",
}

这里的curState是字符串,例如curState = "hello"。你尝试创建一个对象数组,如下所示:

let arr = [];
const [cards, setCards] = useState(arr);

for (let i = 0; i < curState.length; i++) {
  arr.push({
    id: i,
    letter: curState[i],
    color: colorObj[curState[i]],
    isPressed: false,
  });
}

然后,你将最终的数组在卡片组件中渲染,如下所示:

<div className="flex items-center justify-center">
  <div className="my-grid">
    {cards.map((item) => (
      <Cards
        color={item.color}
        key={item.id}
        id={item.id}
        text={item.letter}
      />
    )}
  </div>
</div>

卡片组件如下:

import React from "react";
import { BsTrashFill } from "react-icons/bs";
function Cards(props) {
  return (
    <div
      style={{ backgroundColor: props.color }}
      onClick={props.handleClick}
      className="h-20 w-20 text-yellow-100 flex items-center justify-center cursor-pointer relative rounded-xl"
    >
      {props.text}
      <span onClick={props.delete} className="absolute top-2 right-2">
        <BsTrashFill />
      </span>
    </div>
  );
}
Cards.defaultProps = {
  // color: "blue",
};
export default Cards;

请注意,颜色属性设置为卡片组件的样式。但出现问题的原因似乎无法确定。

英文:

How can i add specfic color to each letter in a word , the color of each letter should be same if it is repeating. Like if b is repeating then all b letters should have the same color.

Here is my color obj as key value pair-

const colorObj = 
{
  a: &quot;red&quot;,
  b: &quot;green&quot;,
  c: &quot;blue&quot;,
  d: &quot;violet&quot;,
  e: &quot;yellow&quot;,
  f: &quot;orange&quot;,
  g: &quot;brown&quot;,
  h: &quot;indigo&quot;,
  i: &quot;cadetblue&quot;,
  j: &quot;chocolate&quot;,
  k: &quot;crimson&quot;,
  l: &quot;darkcyan&quot;,
  m: &quot;darkgrey&quot;,
  n: &quot;darkolivegreen&quot;,
  o: &quot;darkorange&quot;,
  p: &quot;darkviolet&quot;,
  q: &quot;deeppink&quot;,
  r: &quot;fuchsia&quot;,
  s: &quot;gold&quot;,
  t: &quot;greenyellow&quot;,
  u: &quot;khaki&quot;,
  v: &quot;springgreen&quot;,
  w: &quot;yellowgreen&quot;,
  x: &quot;sienna&quot;,
  y: &quot;royalblue&quot;,
  z: &quot;peachpuff&quot;,
},

Here curState is the string , for eg curState = "hello"
i tried to create an array of objects -

  let arr = [];
  const [cards, setCards] = useState(arr);

  for (let i = 0; i &lt; curState.length; i++) {
    arr.push({
      id: i,
      letter: curState[i],
      color: colorObj [curState[i]],
      isPressed: false,
    });
  }

i was rendering the final array in a card component like this -

&lt;div className=&quot;flex items-center justify-center&quot;&gt;
        &lt;div className=&quot;my-grid&quot;&gt;
          {cards.map((item) =&gt; (
            &lt;Cards
              color={item.color}
              key={item.id}
              id={item.id}
              text={item.letter}
            /&gt;
          ))}
        &lt;/div&gt;
      &lt;/div&gt;

here is the card compoent-

import React from &quot;react&quot;;
import { BsTrashFill } from &quot;react-icons/bs&quot;;
function Cards(props) {
  return (
    &lt;div
      style={{ backgroundColor: props.color }}
      onClick={props.handleClick}
      className=&quot;h-20 w-20 text-yellow-100 flex items-center justify-center cursor-pointer relative rounded-xl&quot;
    &gt;
      {props.text}
      &lt;span onClick={props.delete} className=&quot; absolute top-2 right-2&quot;&gt;
        &lt;BsTrashFill /&gt;
      &lt;/span&gt;
    &lt;/div&gt;
  );
}
Cards.defaultProps = {
  // color: &quot;blue&quot;,
};
export default Cards;

note the color prop is set to as the style for the card component.
but for some reason it dosen't seem to work.

答案1

得分: 1

I'm not sure why your code doesn't work When I tried the code in sandbox, it does render properly. One issue that I can think of is that in your code, where you loop through the string, once you finish the loop, you need to set the cards value to the array returned.

But again, I cannot be sure about that since you have not included the complete code. But here's the solution that I used. Maybe you can compare the code and then fix it.

import "./styles.css";
import React, { useState, useEffect } from "react";
import { BsTrashFill } from "react-icons/bs";

const colorObj = {
  a: "red",
  b: "green",
  c: "blue",
  d: "violet",
  e: "yellow",
  f: "orange",
  g: "brown",
  h: "indigo",
  i: "cadetblue",
  j: "chocolate",
  k: "crimson",
  l: "darkcyan",
  m: "darkgrey",
  n: "darkolivegreen",
  o: "darkorange",
  p: "darkviolet",
  q: "deeppink",
  r: "fuchsia",
  s: "gold",
  t: "greenyellow",
  u: "khaki",
  v: "springgreen",
  w: "yellowgreen",
  x: "sienna",
  y: "royalblue",
  z: "peachpuff",
};

function Cards(props) {
  return (
    <div
      style={{ backgroundColor: props.color }}
      onClick={props.handleClick}
      className="h-20 w-20 text-yellow-100 flex items-center justify-center cursor-pointer relative rounded-xl"
    >
      {props.text}
      <span onClick={props.delete} className="absolute top-2 right-2">
        <BsTrashFill />
      </span>
    </div>
  );
}

export default function App() {

  const [cards, setCards] = useState([]);

  useEffect(() => {
    let arr = [];
    const curState = 'It workssz';

    for (let i = 0; i < curState.length; i++) {
      arr.push({
        id: i,
        letter: curState[i],
        color: colorObj[curState[i]],
        isPressed: false,
      });
    }
    setCards(arr);
  }, [])

  return (
    <div className="App">
      <div className="flex items-center justify-center">
        <div className="my-grid">
          {cards.map((item) => (
            <Cards
              color={item.color}
              key={item.id}
              id={item.id}
              text={item.letter}
            />
          ))}
        </div>
      </div>
    </div>
  );
}

export { Cards };

Here's the sandbox link.

英文:

I'm not sure why your code doesn't work When I tried the code in sandbox, it does render properly.

One issue that I can think of is that in your code, where you loop through the string, once you finish the loop, you need to set the cards value to the array returned.

But again, I cannot be sure about that since you have not included the complete code. But here's the solution that I used. Maybe you can compare the code and then fix it.

import &quot;./styles.css&quot;;
import React, {useState, useEffect} from &quot;react&quot;;
import { BsTrashFill } from &quot;react-icons/bs&quot;;
const colorObj = 
{
a: &quot;red&quot;,
b: &quot;green&quot;,
c: &quot;blue&quot;,
d: &quot;violet&quot;,
e: &quot;yellow&quot;,
f: &quot;orange&quot;,
g: &quot;brown&quot;,
h: &quot;indigo&quot;,
i: &quot;cadetblue&quot;,
j: &quot;chocolate&quot;,
k: &quot;crimson&quot;,
l: &quot;darkcyan&quot;,
m: &quot;darkgrey&quot;,
n: &quot;darkolivegreen&quot;,
o: &quot;darkorange&quot;,
p: &quot;darkviolet&quot;,
q: &quot;deeppink&quot;,
r: &quot;fuchsia&quot;,
s: &quot;gold&quot;,
t: &quot;greenyellow&quot;,
u: &quot;khaki&quot;,
v: &quot;springgreen&quot;,
w: &quot;yellowgreen&quot;,
x: &quot;sienna&quot;,
y: &quot;royalblue&quot;,
z: &quot;peachpuff&quot;,
};
function Cards(props) {
return (
&lt;div
style={{ backgroundColor: props.color }}
onClick={props.handleClick}
className=&quot;h-20 w-20 text-yellow-100 flex items-center justify-center cursor-pointer relative rounded-xl&quot;
&gt;
{props.text}
&lt;span onClick={props.delete} className=&quot; absolute top-2 right-2&quot;&gt;
&lt;BsTrashFill /&gt;
&lt;/span&gt;
&lt;/div&gt;
);
}
export default function App() {
const [cards, setCards] = useState([]);
useEffect(() =&gt; {
let arr = [];
const curState = &#39;It workssz&#39;;
for (let i = 0; i &lt; curState.length; i++) {
arr.push({
id: i,
letter: curState[i],
color: colorObj [curState[i]],
isPressed: false,
});
}
setCards(arr);
},[])
return (
&lt;div className=&quot;App&quot;&gt;
&lt;div className=&quot;flex items-center justify-center&quot;&gt;
&lt;div className=&quot;my-grid&quot;&gt;
{cards.map((item) =&gt; (
&lt;Cards
color={item.color}
key={item.id}
id={item.id}
text={item.letter}
/&gt;
))}
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
);
}
export { Cards };

Here's the sandbox link

huangapple
  • 本文由 发表于 2023年3月21日 00:28:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定