如何使用 React Hooks 单独更改文本的颜色?

How can I change the color of the text separately with react hooks?

我希望 link 分开工作

现在颜色一起变了

这是我的代码

const ChatHeader = ({ location: { pathname } }) => {
  const [color, setColor] = useState("black");
  const [isBlack, setIsBlack] = useState(true);
  const changeColor = (e) => {
    setIsBlack(!isBlack);
    setColor(isBlack ? "#CCCCCC" : "black");
  };
  return (
    <>
      <ChatTexts>
        <ChatText
          current={pathname === "/chats"}
          style={{ color: color }}
          onClick={changeColor}
        >
          <ChatLinks to="/chats">채팅</ChatLinks>
        </ChatText>
        <OpenChateText
          current={pathname === "/openchats"}
          style={{ color: color }}
          onClick={changeColor}
        >
          <ChatLinks to="/openchats">오픈채팅</ChatLinks>
        </OpenChateText>
      </ChatTexts>
    </>
  );
};

如何改变 ChatText 和 OpenChateText 的颜色?

如果我输入“/chats”link,我希望“/chats”字母颜色为黑色,“/openchats”link 字母颜色为灰色。

相反,当您输入“/openchats”link时,我希望“/openchats”link字母颜色为黑色,“/chats”link字母颜色为灰色。

您可以放弃状态和 onClick handlers/callbacks 并使用 pathname 直接导出“活动”颜色。

const ChatHeader = ({ location: { pathname } }) => {
  return (
    <>
      <ChatTexts>
        <ChatText
          current={pathname === "/chats"}
          style={{ color: pathname === "/chats" ? "black" : "#cccccc" }}
        >
          <ChatLinks to="/chats">채팅</ChatLinks>
        </ChatText>
        <OpenChateText
          current={pathname === "/openchats"}
          style={{ color: pathname === "/openchats" ? "black" : "#cccccc" }}
        >
          <ChatLinks to="/openchats">오픈채팅</ChatLinks>
        </OpenChateText>
      </ChatTexts>
    </>
  );
};

更小的优化 DRY

const ChatHeader = ({ location: { pathname } }) => {
  const getStyle = (path) => ({
    color: pathname === path ? "black" : "#cccccc",
  });
  return (
    <>
      <ChatTexts>
        <ChatText
          current={pathname === "/chats"}
          style={getStyle("/chats")}
        >
          <ChatLinks to="/chats">채팅</ChatLinks>
        </ChatText>
        <OpenChateText
          current={pathname === "/openchats"}
          style={getStyle("/openchats")}
        >
          <ChatLinks to="/openchats">오픈채팅</ChatLinks>
        </OpenChateText>
      </ChatTexts>
    </>
  );
};