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

news/2024/7/3 17:12:06

盖茨比乔布斯

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

盖茨比乔布斯


http://www.niftyadmin.cn/n/3648866.html

相关文章

android热修复——自己做个热修复

类的加载机制 需要注意的地方 1.每次生成之后一定要测试&#xff1b;2.尽量的不要分包&#xff0c;不要分多个dex3.混淆的时候&#xff0c;设计到NDK AndFix.java 不要混淆4.生成包之后一般会加固什么的&#xff0c;这个时候生成的差分包&#xff0c;一定要在之前去生成。5.…

Android系统权限配置详解

Android 权限控制代码分析 前在文章介绍过android系统管理层次&#xff1a;http://blog.csdn.net/andyhuabing/article/details/7030212 &#xff0c;这里就核心代码分析一下 android系统充分利用了linux的用户权限管理方法&#xff0c;所以如果需要移植到其它系统&#xff0c…

自己动手搭建数据库框架

首先IDaoSupport接口&#xff0c;有查询&#xff0c;插入单条数据&#xff0c;批量插入&#xff0c;删除&#xff0c;更新 public interface IDaoSupport<T> {void init(SQLiteDatabase sqLiteDatabase, Class<T> clazz);// 插入数据public long insert(T t);// 批…

关于软件的架构设计

好的开始相当于成功一半 开始之初的架构设计决定着软件产品的生死存亡。“好的开始相当于成功一半”。 开始的架构设计也是最难的&#xff0c;需要调研同类产品的情况以及技术特征&#xff0c;了解当前世界上对这种产品所能提供的理论支持和技术平台支持。再结合自己项目的特点…

javascript递归_通过JavaScript了解递归和记忆

javascript递归In this article, you’re going to learn how to use recursive programming, what it is, and how to optimize it for use in algorithms. We’ll be using JavaScript as our programming language of choice to understand the concept of recursion. 在本文…

[C#][正则表达式]寻找匹配的Groups的几种方法

寻找匹配的Groups的几种方法示例&#xff1a;// // 两种大方法: // MatchCollection<->Matches // Match<->Match方式 // // 第一大种&#xff1a; MatchCollection mMCollection oRegex.Matches(strHTMLContent); if(mMCollection.Count > 1) { forea…

Apollo Boost简介

With as much as we’ve gone over creating APIs with GraphQL and Prisma in previous articles, we’ve never actually applied our custom backend to a client-side app. In this article, you’ll learn how to let your user interact with your backend through queri…

成就Android英才之路

著作权归作者所有。商业转载请联系作者获得授权&#xff0c;非商业转载请注明出处。作者&#xff1a;王宇龙链接&#xff1a;http://www.zhihu.com/question/19759722/answer/29213925来源&#xff1a;知乎由于工作需要大量修改framework代码, 在AOSP(Android Open Source Proj…