Heim  >  Fragen und Antworten  >  Hauptteil

Farbvariable ändert sich für jedes zugeordnete Element, auf das Tailwind reagiert

Ich möchte, dass sich die Farbe des vorherigen Elements nicht ändert, sobald ich ein weiteres Element zur Liste hinzufüge.

const NoteItem = ({ note }) => {
  const { colors, randomColorFunction } = useContext(AppContext);
  const color = randomColorFunction(colors);
  return (
    <div
      className={`flex flex-col min-h-28  py-6 justify-between px-3 rounded-md whitespace-pre-wrap break-words`}
      style={{ backgroundColor: `${color}` }}
    >
      <span className="font-bold text-3xl">{note.title}</span>
      <span>{note.content}</span>
      <small className="text=xl">{note.date}</small>
    </div>
  );
};

P粉982009874P粉982009874170 Tage vor367

Antworte allen(1)Ich werde antworten

  • P粉237125700

    P粉2371257002024-04-04 18:40:53

    你可以通过两种方式解决这个问题

    1。使用引用

    import { useRef } from "react";
    
    const NoteItem = ({ note }) => {
      const { colors, randomColorFunction } = useContext(AppContext);
      const color = useRef(randomColorFunction(colors));
    
      return (
        
    ...
    ); };

    2.使用状态

    import { useState } from "react";
    
    const NoteItem = ({ note }) => {
      const { colors, randomColorFunction } = useContext(AppContext);
      const [color] = useState(randomColorFunction(colors));
    
      return (
        
    ...
    ); };

    如果您不想更改颜色,我认为 useRef 更合适。

    请参阅此处实时预览

    Antwort
    0
  • StornierenAntwort