上下文在React Native中无法正常工作



这是我的上下文文件:

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**的值。因此,**动画视图**可以正常工作,这完全取决于打开的的值

Opened在所有组件中都可读,没有问题。但是**toggleOpened**根本不起作用。知道吗?

为了正确使用上下文,您需要至少有两个组件协同工作,一个组件渲染提供程序,另一个组件使用该上下文。

您试图在提供和使用上下文的同时,尝试将使用者组件向下移动一个位置到层次结构中。

例如,在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中使用上下文,毕竟,我们希望通过使用上下文来避免将道具传递给孩子,对吧?

我为您创建了一个片段,看看我们如何正确使用上下文

最新更新