Typescript 和 Emotion js,条件道具

Typescript and Emotion js, conditional props

基本上在我的 redux 商店中我有一个布尔状态,我在应用时通过道具使用条件 css 但出于某种原因我的:

  background: $ {(props: HamburguerProps) => (props.open? 'red': 'pink')};

即使状态为真或假也始终保持红色

多伦多证券交易所:

interface RootState {
  sideBarStatus: boolean;
}

interface SideBar {
  isOpen: boolean;
}

const LogoNavigation: React.FC<SideBar> = ({ isOpen }) => {
  const dispatch = useDispatch();
  return (
    <LogoSide open={isOpen} xd={isOpen ? 'blue' : 'pink'}>
      <img src={Logo} alt="Logo Elo Ghost" />
      <Hamburguer
        open={isOpen}
        onClick={() => dispatch(toggleSide(!isOpen))}
      >
        <div />
        <div />
        <div />
      </Hamburguer>
    </LogoSide>
  );
};
const SideNavigation: React.FC = () => {
  // const { sideIsOpen } = useSelector((RootState) => RootState.toggleSide);
  const selectIsOpen = (state: RootState) => state.sideBarStatus;
  const sideBarStatus = useSelector(selectIsOpen);
  console.log('sideBar', sideBarStatus);
  return (
    <SideNav>
      <LogoNavigation isOpen={sideBarStatus} />
    </SideNav>
  );
};

CSS:

import styled from '@emotion/styled';

type HamburguerProps = {
  open: boolean;
};
export const LogoSide = styled.div<HamburguerProps>`
  display: flex;
  position: relative;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 60px;
  background: ${(props: HamburguerProps) => (props.open ? 'red' : 'pink')};
  img {
    height: 50px;
  }
`;

一个 gif 示例,其中显示我的状态从 true 变为 false,但我的风格没有改变:

示例:

https://codesandbox.io/s/great-galileo-zp3e7?file=/src/

isOpen 不是 boolean,它是一个包含 sideIsOpen 键和 boolean 值的对象。 object 总是真实的,这就是为什么你的背景总是 红色

open={isOpen.sideIsOpen}

甚至更好 - 对选择器使用解构:

const { sideIsOpen } = useSelector(selectIsOpen);

isOpen={sideIsOpen}