I have a simple sidebar where I use transitions for opening/closing the sidebar.

The transitions work when I call my Sidebar component as a function (sidebar 1 in example).
The transitions don't work when I use the Sidebar component as a component (sidebar 2 in example).

Why don't they work in example 2?

const App = (props) => {
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);

  const Sidebar = ({ bg, ...props }) => {
    const width = sidebarCollapsed ? "0px" : "200px";

    return (
      <div
        style={{
          backgroundColor: bg,
          height: "100px",
          width: width,
          transitionDuration: "500ms"
        }}
      />
    );
  };

  return (
    <div>
      <div>
        {/* Sidebar 1 -> function */}
        {Sidebar({ bg: "blue" })}

        {/* Sidebar 2 -> component */}
        <Sidebar bg="red" />

        <button onClick={() => setSidebarCollapsed(!sidebarCollapsed)}>
          Toggle sidebar
        </button>
      </div>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

推荐答案

这就是Reaction DOM的工作方式,如果您想要为它设置动画,您必须通过打开的props .当你试图将state从一个组件传到另一个组件时,你应该总是通过props 来完成.

 const Sidebar = ({ bg, open, ...props }) => {
    const width = open  ? "0px" : "200px";

    return (
      <div
        style={{
          backgroundColor: bg,
          height: "100px",
          width: width,
          transitionDuration: "500ms"
        }}
      />
    );
  };
const App = (props) => {
  const [sidebarCollapsed, setSidebarCollapsed] = React.useState(false);



  return (
    <div>
      <div>
        {/* Sidebar 1 -> function */}
        {Sidebar({ bg: "blue", open: sidebarCollapsed })}

        {/* Sidebar 2 -> component */}
        <Sidebar bg="red" open={sidebarCollapsed}/>

        <button onClick={() => setSidebarCollapsed(!sidebarCollapsed)}>
          Toggle sidebar
        </button>
      </div>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Javascript相关问答推荐

如何禁用附加图标点击的v—自动完成事件

配置WebAssembly/Emscripten本地生成问题

使用Java脚本根据按下的按钮更改S文本

Angular 形式,从DOM中删除不会删除指定索引处的内容,但会删除最后一项

TypeError:无法读取未定义的属性(正在读取';宽度';)

令牌JWT未过期

在D3条形图中对具有相同X值的多条记录进行分组

对具有相似属性的对象数组进行分组,并使用串连的值获得结果

将多个文本框中的输出合并到一个文本框中

如何修复使用axios运行TSC index.ts时出现的错误?

Node.js错误: node 不可单击或不是元素

在没有任何悬停或其他触发的情况下连续交换图像

如何在Java脚本中并行运行for或任意循环的每次迭代

从异步操作返回对象

如何在Reaction中设置缺省值, Select 下拉列表,动态追加剩余值?

暂停后只有一次旋转JS

Rails 7:在不使用导入映射的情况下导入Java脚本

当一条路由在Reaction路由中命中时,如何有条件地渲染两个组件或更改两个插座?

使用Java脚本筛选数组中最接近值最小的所有项

如何将PNG图像放在wix站点的Open Streemap map 上,使PNG图像成为 map 不可分割的一部分?