【问题标题】:Working with react-spring and styled-components使用 react-spring 和 styled-components
【发布时间】:2021-01-09 05:11:20
【问题描述】:

我无法让 react-spring 工作。我对此很陌生,所以我不知道出了什么问题。我试图让导航栏从上到下显示为 40vh,但它似乎没有识别出传递的道具。我使用了 create-react-app 和 react-spring 8.0.27

App.js:

const App = () => {
  const [open, setOpen] = useState(false);

  const navprops = useSpring({
    from: {height: "0"},
    to: {height: "40vh"}
  })

  return (
    <Fragment>
      {open ? <Navbar style={navprops}/> : null}
    </Fragment>

Navbar.js:


const NavBar = styled(animated.nav)`
  width: 100%;
`;

const Navbar = (props) => {
  return (
    <NavBar style={props.style}>
    </NavBar>
  );
};

这基本上是代码。还有更多样式道具,但我想这与功能无关。

animated 和 useSpring 被导入到两个文件中进行测试。感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs styled-components react-spring


    【解决方案1】:

    这是我的解决方案,

    Demo Link

    Navbar.js

    import React from "react";
    import styled from "styled-components";
    import { animated } from "react-spring";
    
    const NavBar = styled(animated.nav)`
      width: 100%;
      background: red;
    `;
    
    export default (props) => {
      return <NavBar style={props.style}></NavBar>;
    };
    

    App.js

    import React, { useState } from "react";
    import { useTransition, config } from "react-spring";
    import Navbar from "./Navbar";
    
    export default function App() {
      const [open, setOpen] = useState(false);
    
      // const navprops = useSpring({
      //   from: { height: "0" },
      //   to: { height: "40vh" },
      //   config: config.wobbly
      // });
    
      const transitions = useTransition(open, null, {
        initial: { height: "0px" }, //Not required
        from: { height: "0px" },
        enter: { height: "40vh" },
        leave: { height: "0px" },
        config: config.wobbly //More configs here https://www.react-spring.io/docs/hooks/api
      });
    
      return (
        <div className="App">
          {transitions.map(
            ({ item, key, props }) => item && <Navbar key={key} style={props} />
          )}
          <br />
          <br />
          <button onClick={() => setOpen(!open)}>Toggle Navbar</button>
        </div>
      );
    }
    

    我认为 useSpring 不适用于未安装的组件。您正在尝试为未安装的组件设置动画。

    根据文档,useTransition 可用于动画安装未安装的组件。

    语法有点复杂,但它们在 react-spring Link Here987654323@ 的第 9 版(候选发布版)中使语法更简单

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 2020-11-03
      • 2021-08-07
      • 2021-07-15
      • 2018-04-14
      • 2019-08-06
      • 1970-01-01
      • 2017-11-18
      • 2017-06-17
      相关资源
      最近更新 更多