我試圖理解 useContext 但我不明白我在這里做錯了什么,我收到錯誤訊息“找不到變數:測驗”但在我正在閱讀的教程中,我從未說過任何關于需要的內容匯入/匯出代碼中的內容以外的內容?謝謝!
應用程式.js
import React, { createContext } from 'react';
const Test = createContext()
export default function App() {
return (
<Test.Provider value="hello">
<Home/>
</Test.Provider> );
}
主頁.js
const Home = () => {
return(
<Test.Consumer>
<View style={styles.homeContainer}>
{value}
</View>
</Test.Consumer>
)
}
uj5u.com熱心網友回復:
您不是Test從匯出App.js,因此您不能在Home.js.
我建議將其移至另一個檔案,例如contexts.js:
import React from 'react';
const Test = React.createContext();
export {Test};
然后你可以做
import {Test} from './contexts';
在您的其他源檔案的兩個(或所有,將來)中參考相同的背景關系型別。
uj5u.com熱心網友回復:
我建議您在單獨的檔案中創建背景關系:
測驗背景關系.js
import { createContext } from 'react';
export const TestContext = createContext();
應用程式.js
import React from 'react';
import { TestContext } from './test-context';
export default function App() {
return (
<TestContext.Provider value="hello">
<Home/>
</TestContext.Provider>
);
}
在 中TestContext.Consumer,您必須提供一個函式來使用背景關系值。
主頁.js
import React from 'react';
import { TestContext } from './test-context';
export default const Home = () => {
return (
<TestContext.Consumer>
value => (
<View style={styles.homeContainer}>
{value}
</View>
)
</TestContext.Consumer>
)
}
uj5u.com熱心網友回復:
如今,在閱讀有關精美圖書館的檔案時,我們經常忘記舊學校的規則。
在你的例子中,Context只是一個 JS 物件,為了訪問Test.Consumer,Test必須在檔案的范圍內。
因此,您必須匯入Test物件(背景關系)才能訪問該Consumer屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/395215.html
上一篇:如何在反應中默認啟用順風暗模式?
