盖茨比乔布斯_在盖茨比中使用React Hooks

盖茨比乔布斯

JavaScript treats functions as first-class citizens. And we can see this in React now more than ever with the introduction of Hooks in version 16.8. They allow for state manipulation and side-effects on functional components.

JavaScript将函数视为一等公民。 随着版本16.8中Hooks的引入,我们现在比以往任何时候都可以在React中看到这一点。 它们允许状态操纵和对功能组件的副作用。

At its core, Gatsby uses vanilla React with all its features. So this means Hooks are available to use with a simple import statement. Let’s take a look at some of the ways we can take advantage of them.

Gatsby的核心功能是使用Vanilla React的所有功能。 因此,这意味着可以将Hooks与简单的import语句一起使用。 让我们看一下我们可以利用它们的一些方法。

入门 (Getting Started)

There isn’t anything, in particular, we’ll need to install. However, it’s necessary to have the latest version of React and Gatsby or at least v16.8+. We can do so by checking out our package.json and finding which version we already have installed.

没有任何东西,特别是我们需要安装。 但是,必须具有最新版本的React和Gatsby或至少v16.8 +。 我们可以通过检出package.json并找到我们已经安装的版本来做到这一点。

If you need to upgrade, we can run the following:

如果您需要升级,我们可以运行以下命令:

$ npm install react@16.8.0 react-dom@16.8.0
# or
$ yarn add react@16.8.0 react-dom@16.8.0

With that, we should be good to go.

这样,我们应该很好。

使用挂钩 (Using Hooks)

Let’s set up a header.js component with a scrolled state and a dropdown menu.

让我们设置一个带有滚动状态和下拉菜单的header.js组件。

Our component will be a fixed header at the top that remains in place while the user scrolls through the page, but displays a box-shadow when the user isn’t at the top. That means our state would be a boolean which toggles based on the current window position. We’ll use native APIs to determine window position.

我们的组件将是顶部的固定标头,当用户滚动页面时该标头将保留在原处,但是当用户不在顶部时,将显示一个框形阴影。 这意味着我们的状态将是一个布尔值,它会根据当前窗口的位置进行切换。 我们将使用本机API确定窗口位置。

src/components/header.js
src / components / header.js
import React, { useState, useEffect } from 'react';
import { Link } from 'gatsby';

const Header = () => {
  // determined if page has scrolled and if the view is on mobile
  const [scrolled, setScrolled] = useState(false);

  // change state on scroll
  useEffect(() => {
    const handleScroll = () => {
      const isScrolled = window.scrollY > 10;
      if (isScrolled !== scrolled) {
        setScrolled(!scrolled);
      }
    };

    document.addEventListener('scroll', handleScroll, { passive: true });

    return () => {
      // clean up the event handler when the component unmounts
      document.removeEventListener('scroll', handleScroll);
    };
  }, [scrolled]);

  return (
    <header data-active={scrolled}>
      <Link to="/">React Hooks on Gatsby</Link>
      <nav>
        <Link to="/about/">About</Link>
        <Link to="/contact/">Contact Us</Link>
      </nav>
    </header>
  );
};

export default Header;

The window.scrollY property returns the number of pixels that have passed vertically on scroll. We compare that value to 10 pixels and we get a boolean value that will tell us if the user has moved the document or not. We then wrap the conditional property around a function that updates the scrolled state whenever the user scrolls through the site. This function is then passed to an event listener on the document.

window.scrollY属性返回滚动时垂直通过的像素数。 我们将该值与10像素进行比较,然后得到一个布尔值,该值将告诉我们用户是否移动了文档。 然后,我们将条件属性包装在一个函数上,该函数将在用户滚动网站时更新scrolled状态。 然后将此函数传递到文档上的事件侦听器。

All of this will live inside the useEffect hook, which will return a removeEventListener on the document to clean up the event handler when the component unmounts. The useEffect hook allows us to perform side effects on our component. The effect will fire after every completed render by default, however, we can pass a second argument as an array of values on which the effect depends on to fire. In our case, [scrolled].

所有这些都将存在于useEffect挂钩中,该挂钩将在文档卸载时在文档上返回removeEventListener ,以清理事件处理程序。 useEffect挂钩允许我们在组件上执行副作用。 默认情况下,效果将在每次完成渲染后触发,但是,我们可以将第二个参数作为值依赖的值的数组传递。 在我们的例子中, [scrolled]

With that, we can add an identifying attribute to our HTML to determine the state of the element. We’ll use a data-active attribute with the boolean from the scrolled state. And in our CSS, we can add the box-shadow effect using the attribute selector.

这样,我们可以在HTML中添加一个标识属性来确定元素的状态。 我们将使用data-active属性,并将其与scrolled状态的布尔值一起使用。 并且在我们CSS中,我们可以使用属性选择器添加box-shadow效果。

src/styles/main.scss
src /样式/main.scss
header {
  position: fixed;
  top: 0;
  transition: box-shadow .3s ease;
  width: 100%;

  &[data-active='true'] {
    box-shadow: 0 2px 8px rgba(152,168,188,.2);
  }
}

The same styling can be used with styled-components. Swapping the header selector with the component’s tagged template literal will provide the same functionality.

样式组件可以使用相同的样式。 将header选择器与组件的带标签的模板文字交换将提供相同的功能。

挂钩和用户输入 (Hooks and User Input)

We’ll take this example a step further and add a dropdown menu accessible via a toggle button. We can keep most of what was already made and just modify the state change properties. The property will be renamed to state and setState while taking an object with our various state variables.

我们将进一步扩展该示例,并添加一个通过切换按钮访问的下拉菜单。 我们可以保留大部分已完成的内容,而只需修改状态更改属性。 在使用带有各种状态变量的对象时,该属性将重命名为statesetState

Updating state would be a little different in this case. First, we need to pass the previous state as a spread operator, followed by the updated value. This is because, unlike class components, functional ones will replace updated objects instead of merging them.

在这种情况下,更新状态会有所不同。 首先,我们需要将以前的状态作为散布运算符传递,然后是更新后的值。 这是因为,与类组件不同,功能组件将替换更新的对象,而不是合并它们。

src/components/header.js
src / components / header.js
import React, { useState, useEffect } from 'react';
import { Link } from 'gatsby';

import Dropdown from './dropdownMenu';

const Header = () => {
  // determined if page has scrolled and if the view is on mobile
  const [state, setState] = useState({
    scrolled: false,
    visible: false,
  });

  // change state on scroll
  useEffect(() => {
    const handleScroll = () => {
      const isScrolled = window.scrollY > 10;
      if (isScrolled !== state.scrolled) {
        setState({
          ...state,
          scrolled: !state.scrolled,
        });
      }
    };
    document.addEventListener('scroll', handleScroll, { passive: true });
    return () => {
      // clean up the event handler when the component unmounts
      document.removeEventListener('scroll', handleScroll);
    };
  }, [state.scrolled]);

  // toggle dropdown visibility
  const toggleVisibility = () => {
    setState({
      ...state,
      visible: !state.visible,
    });
  };

  return (
    <header data-active={state.scrolled}>
      <Link to="/">React Hooks on Gatsby</Link>
      <nav>
        <Link to="/about/">About</Link>
        <Link to="/contact/">Contact Us</Link>
        <button onClick={toggleVisibility} type="button">
          Solutions
        </button>
        <Dropdown
          aria-hidden={!state.visible}
          data-active={state.visible}
        />
      </nav>
    </header>
  );
};

export default Header;

We want to have the user click a button that will open up an additional menu. When the Solutions button is clicked, it’ll toggle the visible boolean. This boolean is passed to the aria-hidden and data-active attributes for use in our CSS.

我们希望用户单击一个按钮,这将打开一个附加菜单。 单击“ 解决方案”按钮时,它将切换visible布尔值。 此布尔值传递给aria-hiddendata-active属性,供我们CSS使用。

src/styles/main.scss
src /样式/main.scss
// the section element is our <Dropdown /> component

header {
  top: 0;
  transition: box-shadow .3s ease;

  &[data-active='true'] {
    box-shadow: 0 2px 8px rgba(152,168,188,.2);
  }

  &,
  section {
    position: fixed;
    width: 100%;
  }

  nav,
  section {
    overflow: hidden;
  }

  section {
    height: 0;
    left: 0;
    opacity: 0;
    right: 0;
    top: 5.5rem;
    transition: all .3s ease-in-out;
    visibility: hidden;

    &[data-active='true'] {
      height: auto;
      opacity: 1;
      visibility: visible;
    }
  }
}

结论 (Conclusion)

With Hooks, we get all the benefits of class components with the familiarity of functional ones. Gatsby takes full advantage of that. I recommend you take a look at all the Hooks available in the React documentation. And you can even dive into building your own hooks!

使用Hooks,我们可以在熟悉功能组件的同时获得类组件的所有好处。 盖茨比充分利用了这一点。 我建议您看一下React文档中所有可用的Hook 。 您甚至可以潜入自己的钩子中

翻译自: https://www.digitalocean.com/community/tutorials/gatsbyjs-react-hooks-gatsby

盖茨比乔布斯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值