【问题标题】:With React Styled Components, how do I declare the colour based on state collected via useSelector?使用 React Styled Components,如何根据通过 useSelector 收集的状态声明颜色?
【发布时间】:2021-07-01 04:26:40
【问题描述】:

我在我的应用程序中使用样式化组件。我正在使用 React-Redux 通过 useSelector 收集状态,此状态返回 0 或 1 - 0 告诉我应用当前处于亮模式,1 告诉我应用当前处于暗模式。

如何根据值编辑样式?我已经尝试了以下...

const Logo = styled(motion.h1)`
  color: ${themeColour ? "white" : "black"};
`;

但是,这不起作用,因为变量存在于函数中。然后我尝试像这样在 JSX 中直接设置 h1 组件的样式...

<h1 style={{color: ${themeColour ? "white" : "black"}}}>

我收到以下错误...

"./src/components/Nav.js
SyntaxError: C:\Users\james\Documents\Web Development\Portfolio\Project 1 - RelaxStation\Code\relax-station\src\components\Nav.js: Unexpected token, expected "," (14:26)"

有人可以帮我解决这个问题吗?下面是我的组件的完整代码(请注意我在这里粘贴代码时无法正确缩进,但在 Visual Studio Code 中是正确的)...

// Libraries
import styled from "styled-components";
import { motion } from "framer-motion";

// Redux
import { useSelector } from "react-redux";

const Nav = () => {
  // Get current theme colour code - Gives a 0 for light mode or a 1 for dark mode
  const themeColour = useSelector((state) => state.theme);

  return (
<StyledNav>
  <Logo>
    Relax<span>Station</span>
  </Logo>

  <div className="main">
    <h4>MAIN</h4>
    <ul className="main-links">
      <li>Home</li>
      <li>Artists</li>
      <li>Albums</li>
    </ul>
  </div>
  <div className="playlists">
    <h4>PLAYLISTS</h4>
    <ul className="playlist-links">
      <li>Early morning</li>
      <li>Studying</li>
      <li>Driving</li>
      <li>Ambience</li>
    </ul>
  </div>
</StyledNav>
  );
};

const StyledNav = styled(motion.nav)`
  position: static;
  width: 10rem;
  top: 0;
  left: 0;
  min-height: 95vh;
  border: 2px solid rgba(255, 255, 255, 0.125);
`;

const Logo = styled(motion.h1)`
  color: ${themeColour ? "white" : "black"};
`;

export default Nav;

提前致谢

【问题讨论】:

    标签: reactjs react-redux jsx styled-components


    【解决方案1】:

    渲染时需要将 themeColor 作为道具传递给 Logo 组件

      <Logo themeColor={themeColor}>
        Relax<span>Station</span>
      </Logo>
    

    然后将它与样式组件一起使用

    const Logo = styled(motion.h1)`
      color: ${props => props.themeColour? "white" : "black"};
    `;
    

    对于 h1 标记,您的代码不起作用,因为您的语法不正确

    下面是正确的用法

    <h1 style={{color: themeColour ? "white" : "black"}}>
    

    【讨论】:

    • 一切都很好,非常感谢您的帮助。我不知道您可以将这样的道具传递给样式化的组件。再次感谢! :)
    • 很高兴能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 2020-12-25
    • 2020-05-29
    • 2018-12-02
    • 2019-11-03
    • 2017-11-18
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多