這是我的背景關系檔案:
import React from 'react';
import { createContext, useState } from 'react';
export const TabContext = createContext({
opened: false,
toggleOpened: () => {},
});
export const TabContextProvider = ({ children }) => {
const [opened, setOpened] = useState(false);
const toggleOpened = () => {
setOpened(!opened);
};
return (
<TabContext.Provider value={{ opened, toggleOpened }}>
{children}
</TabContext.Provider>
);
};
我的簡化 App.js 檔案:(匯入了必要的檔案)
const Tab = createBottomTabNavigator();
export default function App() {
const buttonCtx = useContext(TabContext);
return (
<>
<TabContextProvider>
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen
name='Action'
component={ActionScreen}
options={{
tabBarButton: () => (
<ActionButton
opened={buttonCtx.opened}
toggleOpened={buttonCtx.toggleOpened}
/>
),
}}
/>
</Tab.Navigator>
</NavigationContainer>
</TabContextProvider>
</>
);
}
和簡化的 ActionButton 組件:
export default function ActionButton({ opened, toggleOpened }) {
return (
<View style={styles.container}>
<View style={styles.box}>
<TouchableWithoutFeedback
onPress={toggleOpened}
style={styles.actionButton}
>
/* With an Animated View inside */
</TouchableWithoutFeedback>
</View>
</View>
);
}
基本上,**toggleOpened **應該在 true 和 false 之間切換變數 **opened ** 的值。所以 **AnimatedView ** 可以正常作業,這完全取決于 opens 的值。
Opened在所有組件中都是可讀的,這沒問題。但是 **toggleOpened ** 根本不起作用。任何想法?
uj5u.com熱心網友回復:
為了正確使用背景關系,您需要至少有兩個組件一起作業,一個呈現提供者,一個后代使用該背景關系。
您正在嘗試同時提供和使用背景關系,嘗試將消費者組件向下移動到層次結構中。
例如,您App.js可以創建一個消費者組件來包裝您的 ActionButton,然后像您一樣將背景關系傳遞給它:
export default function App() {
return (
<>
<TabContextProvider>
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen
name="Action"
component={ActionScreen}
options={{
tabBarButton: () => <ActionButtonWrapper />
}}
/>
</Tab.Navigator>
</NavigationContainer>
</TabContextProvider>
</>
);
}
const ActionButtonWrapper = () => {
const { opened, toggleOpened } = useContext(TabContext);
return (
<>
<ActionButton
opened={opened}
toggleOpened={toggleOpened}
/>
</>
);
};
但是,我會直接在 ActionButton 中使用背景關系,畢竟,我們希望通過使用背景關系來避免將道具傳遞給孩子,對吧?
我為您創建了一個片段,以了解我們如何正確使用背景關系
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521109.html
上一篇:ReactNative上傳圖片
