【问题标题】:React.useContext in styled function with styled components带有样式组件的样式函数中的 React.useContext
【发布时间】:2020-01-17 23:59:18
【问题描述】:

我目前正在使用useContext 在函数内的元素中设置className。比如……

const Wrapper = styled.header`
  background: transparent;
  &.active {
    background: black;
  }
`;

const Header = () => {
  const { isScrolling } = useContext(GlobalConsumer);
  return (
    <Wrapper className={isScrolling ? 'active' : ''}>
      Header
    </Wrapper>
  );
};

但是,如何在不设置className 的情况下获得相同的结果?比如useContext如何在styled函数内部作为...

const Wrapper = styled.header`
  background: ${isScrolling ? 'black' : 'transparent'};
`;

另外,我想在styled 函数中访问const { isScrolling } = useContext(GlobalConsumer);,而不是从函数Header 传递道具

【问题讨论】:

    标签: javascript reactjs react-hooks styled-components


    【解决方案1】:

    我不认为你可以在 styled 函数中做到这一点,但至少你可以将 className 更改为 prop:

    import styled, { css } from 'styled-components';
    
    const Wrapper = styled.header`
      background: transparent;
      ${props => props.active && css`
          background: black;
      `}
    `;
    
    const Header = () => {
      const { isScrolling } = useContext(GlobalConsumer);
      return (
        <Wrapper active={isScrolling}>
          Header
        </Wrapper>
      );
    };
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 2020-03-14
      • 2018-07-26
      • 2021-12-16
      • 2019-08-20
      • 1970-01-01
      • 2020-10-03
      • 2019-08-23
      • 2018-05-10
      相关资源
      最近更新 更多