react 组件中使用组件_React如何将上下文与功能组件一起使用

react 组件中使用组件

When it gets too complicated to share the state between all React components that need it, Context comes to the rescue. Here’s a short guide on how to use context with functional components and hooks in React.

当它变得太复杂而无法在需要它的所有React组件之间共享状态时,Context就可以解决。 这是有关如何在React中将上下文与功能组件和挂钩一起使用的简短指南。

当你应该使用React Context (When shoud you use React Context)

React’s Context is a solution for use cases where you need to share state between multiple components. Without Context, all components that want to use the same state would have to have a common parent component that would pass the state down through props.

React的Context是用于需要在多个组件之间共享状态的用例的解决方案。 如果没有Context,则所有希望使用相同状态的组件都必须具有一个公共父组件,该组件将通过props将状态向下传递。

This is fine if there are few components that need to use the same state and they all have a common parent which can store it. But once you have too many components that need the same state and/or they are too far apart in the React component tree, passing the state down through props becomes a nightmare. It’s tedious to write, complicated to understand and difficult to maintain.

如果很少有组件需要使用相同的状态,并且它们都有一个可以存储状态的公共父节点,那么这很好。 但是一旦您有太多需要相同状态的组件和/或它们在React组件树中相距太远,将状态通过props传递就变成了一场噩梦。 写起来很麻烦,理解起来很复杂而且很难维护。

If you encounter this issue, consider replacing your state with React Context instead.

如果遇到此问题,请考虑用React Context代替您的状态。

It’s pretty simple to set up a Context once you get a hang of it. However, it’s also easy to forget how to do it since you generally need very few (or perhaps only one) Context in your React app. I had to re-learn how to do it, so I thought I could help both myself and others by writing the process down.

一旦掌握了上下文,就可以很容易地设置它。 但是,也很容易忘记如何做,因为您在React应用程序中通常只需要很少(或也许只有一个)上下文。 我不得不重新学习如何做,因此我认为通过写下该过程可以对自己和他人都有所帮助。

Context works in a similar way to React state, but it isn’t necessarily bound to a concrete component. Instead, all components that need to access the information stored in the context can simply call the useContext hook of the desired Context.

上下文的工作方式类似于React状态,但不一定绑定到具体组件。 相反,所有需要访问存储在上下文中的信息的组件都可以简单地调用所需Context的useContext钩子。

If the Context isn’t bound to a particular component, it’s typically stored in a separate module (file). For easier navigation, you can group all such React Context instances in a common folder, separate from your React components.

如果上下文未绑定到特定组件,则通常将其存储在单独的模块(文件)中。 为了更轻松地导航,您可以将所有这样的React Context实例分组在一个公共文件夹中,与React组件分开。

First, we’ll take a look at defining the Context and then we’ll go though where to place it and how to use it in your components.

首先,我们将研究定义Context,然后遍历放置在何处以及如何在组件中使用它。

定义上下文 (Defining a Context)

Similarly to state, Context is created using a createContext function. The function takes the initial value of the Context as a parameter and returns the Context created.

与状态类似,使用createContext函数创建上下文。 该函数将Context的初始值作为参数,并返回创建的Context。

import React from 'react';
const ExampleContext = React.createContext({});

Notice that, unlike state, context doesn’t have a setContext function that would allow you to change the value of the Context. Instead, each Context uses a Provider component that receives a value. This value is set as the value of the Context and can be accessed by all the children components.

请注意,与状态不同,上下文没有设置setContext函数,该函数可让您更改Context的值。 而是,每个上下文都使用接收值的提供程序组件。 此值设置为Context的值,并且所有子组件都可以访问该值。

export function ExampleContextProvider(props) {


// you can insert some code that calculates and changes the value of the context here


    return (
        <ExampleContext.Provider value={{}}>  //here you can provide a new value for the context
            {props.children}
        </ExampleContext.Provider>
    );
}

Finally, to enable your components to consume the contents of the context, you also need to create a useContext hook. This hook can be used by the components that need to access the Context’s value.

最后,要使您的组件能够使用上下文的内容,还需要创建一个useContext挂钩。 需要访问上下文值的组件可以使用此钩子。

export const useExampleContext = () => React.useContext(ExampleContext);

Here’s an example of a simple Context that provides the information about whether it’s currently daytime:

这是一个简单的上下文示例,提供了有关当前是否是白天的信息:

import React from 'react';


const DaylightContext = React.createContext({});


export function DaylightContextProvider(props) {
  const currentDate = new Date();
  const hour = currentDate.getHours();
  const isDaylight = hour > 8 || hour < 20;
  
  return (
    <DaylightContext.Provider value={{ isDaylight: isDaylight }}>
      {props.children}
    </DaylightContext.Provider>
  );
}


export const useDaylightContext = () => React.useContext(DaylightContext);

The Context Provider can have far more complex ways of determining the value to be passed down to its children. The Context Provider itself can have a state and the value of the Provider’s state can then be passed down through the Context.

上下文提供者可以采用更为复杂的方法来确定要传递给子元素的值。 上下文提供者本身可以具有状态,然后可以通过上下文向下传递提供者状态的值。

Note that you need to export the Context Provider and the useContext hook you created. The next section will cover more on how to utilise them in your React app.

请注意,您需要导出Context Provider和创建的useContext钩子。 下一节将详细介绍如何在您的React应用程序中使用它们。

使用上下文 (Using the Context)

All components that need access to the Context should be rendered as children of the Context Provider. The Provider will then provide the value that its children can access.

所有需要访问上下文的组件都应作为上下文提供者的子级呈现。 然后,提供程序将提供其子级可以访问的值。

So the first thing you need to do is identify the parent component that contains all the components which need to use the Context and render the Provider there.

因此,您需要做的第一件事就是确定父组件,该父组件包含所有需要使用Context并在其中呈现Provider的组件。

Since the Context will generally hold the information that’s needed in many components, it’s common to render the Provider within the top level App component. Here’s an example:

由于上下文通常会包含许多组件中所需的信息,因此通常在顶级App组件中呈现Provider。 这是一个例子:

import React from 'react';
// other imports
import { DaylightContextProvider } from './data/context/daylight-context';


function App() {
  return (
    // …
    <DaylightContextProvider>
      // …
      // components that use the Context need to be rendered as its children in the React tree
    </DaylightContextProvider>
    // …
  );
}


export default App;

Finally, the value from the Context can be accessed through the useContext hook.

最后,可以通过useContext挂钩访问Context中的值。

import React from 'react';
import { useDaylightContext } from '../../data/context/daylight-context';


export function ExampleComponent(props) {
  const daylight = useDaylightContext();
  
  if (daylight.isDaylight) {
    // …
  }


  return (
    // …
  );
}

The Context in this example only contains one boolean value, but Context isn’t limited to simple values and can contain complex objects, just like state.

在此示例中,上下文仅包含一个布尔值,但是上下文不限于简单的值,并且可以包含复杂的对象,就像状态一样。

And that’s all you need to get your Context up and running in React! You can look for more information on this topic in the official documentation.

这就是在React中启动并运行Context所需要的一切! 您可以在官方文档中找到有关此主题的更多信息。

I hope this will help you get started with React Context. Thank you for reading!

我希望这将帮助您开始使用React Context。 感谢您的阅读!

备忘单 (Cheat Sheet)

Here’s a short summary on how to get a working React Context.

这是有关如何获得有效的React Context的简短摘要。

To set up your Context:

设置上下文:

  • create a Context using React.createContext()

    使用React.createContext()创建一个上下文
  • create a Context Provider that renders the context

    创建一个渲染上下文的Context Provider
  • create a React.useContext hook

    创建一个React.useContext钩子

To use your context:

要使用您的上下文:

  • render the Context Provider in the parent component (commonly the top-level App component)

    在父组件(通常是顶级App组件)中呈现Context Provider
  • use the useContext hook to get the value from the Context in your components

    使用useContext挂钩从组件中的Context获取值

翻译自: https://medium.com/analytics-vidhya/react-how-to-use-context-with-functional-components-240a8ec4126a

react 组件中使用组件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值