【问题标题】:Why is the flex-value not updating in the styled-component?为什么样式组件中的 flex-value 没有更新?
【发布时间】:2020-01-30 02:59:45
【问题描述】:

我有一个侧边栏和一些主要内容。主要内容占据了屏幕的大部分,而侧边栏应该只占一小部分。我有一个父容器,它是一个 flexbox。两个子元素(侧边栏和主要内容)都是 div 元素。

侧边栏默认关闭

问题:切换侧边栏不会按预期展开侧边栏

我检查过的东西:

  1. 侧边栏 CSS 中的 Flex 值正在正确更新
  2. 边栏事件被触发,isOpen 钩子被正确更新
// main.ts
import styled from 'styled-components';

export const Content = styled.div`
    flex: 4;
    margin-top: 1em;
    margin-bottom: 2em;
    height: 100vh;
`;

export const Container = styled.div`
    display: flex;
`;

// sidebar/styles.ts

import styled from 'styled-components';

interface RootProps {
    isOpen: boolean;
}

export const Root = styled.div<RootProps>`
    padding: 1em;
    background-color: ${DARK};
    flex: ${({ isOpen }: RootProps) => (isOpen ? 1 : 0)};
`;
// sidebar/index.tsx
export const Sidebar: React.FC = () => {
    const dispatch = useDispatch();
    const isOpen = useSidebar();

    const handleOpen = () => dispatch(toggleSidebar());

    return (
        <Root isOpen={isOpen}>
            <Button onClick={handleOpen}>
                CLICK ME
            </Button>
        </Root>
    );
};
// Usage
// Sidebar styles mirror what's in the sidebar styled component file

<Container>
   <Sidebar />
   <Content />
</Container>

预期结果是切换按钮时侧边栏会展开和折叠。没有显示错误消息,并且侧边栏 flex 值正在正确更新。

JSFiddle 仅包含 HTML / CSS,但本质上是所需的效果:https://jsfiddle.net/5dLk9ex3/3/

【问题讨论】:

  • 你想在flex: 0 中实现什么?此外,通过提供可生产的沙箱来更好地提出 CSS 问题,例如 codesandboxcodepen
  • 我只想用flex: 0在侧边栏中显示必要的宽度,用flex: 1我想与主要内容竞争屏幕空间,特别是它的1 / 5
  • 好吧,你自己看看把flex 0改成flex 1不影响
  • 你试过小提琴吗?从 0 变为 1 有理想的效果
  • 你确定你的组件在按钮点击时重新渲染?

标签: css reactjs typescript flexbox styled-components


【解决方案1】:

您的代码的问题在减速器范围内(您的问题不完整),您的Sidebar 在您调度操作后不会重新呈现。

工作示例:

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import styled from 'styled-components';

const Container = styled.div`
  display: flex;
`;

const First = styled.div`
  flex: ${({ isOpen }) => (isOpen ? 1 : 0)};
  background-color: red;
  height: 20px;
`;

const Second = styled.div`
  flex: 4;
  background-color: green;
  height: 20px;
`;

const DEFAULT_INITIAL = false;

const App = () => {
  const [isOpen, setIsOpen] = useState(DEFAULT_INITIAL);

  const onClick = () => {
    console.log('Toggle Sidebar');
    setIsOpen(p => !p);
  };

  return (
    <>
      <Container>
        <First isOpen={isOpen}>FIRST</First>
        <Second>SECOND</Second>
      </Container>
      <button onClick={onClick}>OpenSider</button>
    </>
  );
};

请参考这个答案的第一条评论

【讨论】:

  • 您的问题缺少减速器逻辑和toggleSidebaruseSidebar 实现,您的“错误”在减速器逻辑中。请在减速器范围内重现该问题并提出另一个问题。参考How to create a Minimal, Reproducible Example
【解决方案2】:

我不确定为什么,但将主要内容 div 设置为 min-width: 0 解决了这个问题。查看更多信息:Flex items not shrinking when window gets smaller

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 2010-12-13
    • 2011-01-24
    • 2020-08-05
    • 1970-01-01
    • 2018-10-15
    • 2017-05-23
    • 2018-09-10
    相关资源
    最近更新 更多