[英]How to export context from inside a component(function)?
import React from 'react'
export default function OrderDetailsView() {
const [queryParams] = useSearchParams();
const params: OrderParams = getOrderParams(queryParams);
const extraHeaders: ExtraHeaders = getExtraHeaders(queryParams);
const { data, isLoading } = useOrderParams(params, extraHeaders);
const orderContext = createContext({data, isLoading})
return (
<>
<Provider>
{
List of components
}
</Provider>
</>
);
}
Here I need to use some parameters which I am getting from queryParams and some custom hooks and those params I need to pass through context.在这里,我需要使用一些我从 queryParams 和一些自定义挂钩以及我需要通过上下文传递的参数获取的参数。 But I am unable to export the context as the component itself is a default export and I can't keep the context outside as I need data from custom hook also which I can not keep outside the function. I tried named exports and creating a seperate js file for exports but I will need a function where I will have to keep the custom hooks inside.
但是我无法导出上下文,因为组件本身是默认导出并且我无法将上下文保留在外部,因为我需要来自自定义挂钩的数据,我也不能将其保留在 function 之外。我尝试命名导出并创建一个单独的我需要一个 function 用于导出的 js 文件,但我必须在其中保留自定义挂钩。
You should create a file named OrderContext.ts
and use React.createContext()
in the module scope. So that we can export and import the context easily in any component and custom hooks.您应该创建一个名为
OrderContext.ts
的文件,并在模块 scope 中使用React.createContext()
。这样我们就可以在任何组件和自定义挂钩中轻松导出和导入上下文。
Besides, you can pass the data returned by custom hooks to the value
prop of OrderContext.Provider
component.此外,您可以将自定义钩子返回的数据传递给
OrderContext.Provider
组件的value
prop。 So that the descendant component can get and consume the context value via useContext(OrderContext)
.这样后代组件就可以通过
useContext(OrderContext)
获取和使用上下文值。
Eg例如
OrderContext.ts
: OrderContext.ts
:
import * as React from 'react';
export const OrderContext = React.createContext({
data: undefined,
isLoading: false,
});
OrderDetailsView.tsx
: OrderDetailsView.tsx
:
import * as React from 'react';
import { OrderContext } from './OrderContext';
import { Test } from './Test';
const useOrderParams = (params, extraHeaders) => {
return { data: 'data from API', isLoading: false };
};
export default function OrderDetailsView() {
const params = {};
const extraHeaders = {};
const { data, isLoading } = useOrderParams(params, extraHeaders);
return (
<OrderContext.Provider value={{ data, isLoading }}>
<Test />
</OrderContext.Provider>
);
}
Test.tsx
: Test.tsx
:
import * as React from 'react';
import { OrderContext } from './OrderContext';
export const Test = () => {
const order = React.useContext(OrderContext);
return <div>{order.data}</div>;
};
Demo: stackblitz演示: stackblitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.