我有一個超級簡單的應用程式,比如
import React, { createContext } from 'react';
import { render } from 'react-dom';
import './style.css';
interface IAppContext {
name: string;
age: number;
country: string;
}
const AppContext = createContext<IAppContext | null>(null);
const App = () => {
const contentValue: IAppContext = {
name: 'Paul',
age: 21,
country: 'UK',
};
return (
<AppContext.Provider value={contentValue}>
<div>{name}</div>
</AppContext.Provider>
);
};
render(<App />, document.getElementById('root'));
我只是想使用背景關系,但<div>{name}</div>我得到了錯誤
'name' is deprecated.(6385)
lib.dom.d.ts(19534, 5): The declaration was marked as deprecated here.
Type 'void' is not assignable to type 'ReactNode'.(2322)
index.d.ts(1183, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
const name: void
@deprecated
這是使用背景關系的正確方法嗎?
是我使用打字稿的方式導致了這個錯誤嗎?
uj5u.com熱心網友回復:
通常你會使用 useContext。但是在您當前的示例中,您可以通過更改name為直接使用物件值contentValue.name。
進一步解釋;
背景關系提供者允許您使用一個名為useContext. 當你呼叫這個鉤子時,你傳入了你希望定位的背景關系。在這種情況下,它會是useContext(AppContext)。這使您可以訪問 的value道具<AppContext.Provider />,在您的情況下,此值等于contentValue。
例子;
const MyComponent = () => {
const appContext = useContext(AppContext);
return (
<div>
{appContext.name}
</div>
)
}
uj5u.com熱心網友回復:
Context 基本上是一個非常簡單的狀態管理工具。簡而言之,如果您有一個初始化了某個狀態的父組件,那么在子組件中訪問此狀態所需要做的就是將其作為 props 傳遞。如果您有 10 個子組件,則必須手動執行 10 次,這不太實用。所以 useContext 基本上扭曲了父組件,每個子組件都可以訪問該背景關系。在你的情況下:
interface IAppContext {
name: string;
age: number;
country: string;
}
const AppContext = createContext<IAppContext | null>(null);
const App = () => {
const contentValue: IAppContext = {
name: 'Paul',
age: 21,
country: 'UK',
};
return (
<AppContext.Provider value={contentValue}>
<ChildComponent/> // now let's say you another child component here.
</AppContext.Provider>
);
};
const ChildComponent = () => {
const appContext = useContext(AppContext);
return <div>appContext.name</div>
}
export default Home
如您所見,您也可以訪問子組件中的背景關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408304.html
標籤:
上一篇:反應原生嵌套堆疊導航顯示空螢屏
