在Android的React Native应用程序中,对于某些组件,我想隐藏主StackNavigator的标题。
我对这样使用static navigationOptions
有很多了解:
static navigationOptions = ({navigation}) => {
return {
header: null,
};
};
...但是我只是不知道如何正确使用它。
这里是App.ts
,主StackNavigator位于其中:
import React from 'react';
import {Image, View, StyleSheet, ImageBackground} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import Test from './src/screens/Test/Test';
import LandingPage from './src/screens/LandingPage/LandingPage';
class RootComponent extends React.Component {
render() {
return (
<View>
<LandingPage />
</View>
);
}
}
const RootStack = createStackNavigator(
{
LandingPage: {
screen: RootComponent,
navigationOptions: {
header: null,
},
},
Test: { // The Header of this screen should be hidden as soon as a Button inside Test is pressed
screen: Test,
navigationOptions: {
title: 'Test Title',
},
},
},
{
initialRouteName: 'LandingPage',
},
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
这是组件Test.tsx
:
import React from 'react';
import {Image,View} from 'react-native';
import TestBody from '../../components/organisms/TestBody/TestBody';
type Props = {};
const Test: React.FC<Props> = ({}) => {
const navigationOptions = { // should I do the configuration here?
header: null,
};
function hideHeader() {
// How to set the Header null here?
}
return (
<View>
<TestBody />
<Button
title={'Press me and the header will disappear!'}
onPress={() => hideHeader()}>
</Button>
</View>
);
};
export default Test;
在组件中设置navigationOptions
的方法是否正确?因为如果这样做,则不会应用。我想到的另一种方法是使用Redux
。因此,一旦单击Test
中的按钮,我将创建一个动作,将状态(例如“ hideHeader
”)设置为true,然后访问该状态。但这会是一个好的解决方案吗?我将在哪里访问该州?我会在App.ts
中考虑,但不确定是否正确。
你能帮我吗?
这是Dmitri建议的更新代码:
import React, {useState} from 'react';
import {Button, Image, View} from 'react-native';
import TestBody from '../../components/organisms/TestBody/TestBody';
import {withNavigation} from 'react-navigation';
interface Props {
navigation: any;
}
const Test: React.FC<Props> = ({navigation}) => {
const [showHeader, setShowHeader] = useState(true);
navigation.setParams({
header: showHeader ? undefined : null,
});
function hideHeader() {
setShowHeader(!showHeader);
navigation.setParams({
header: showHeader ? undefined : null,
});
}
return (
<View>
<TestBody />
<Button
title={'Press me and the header will disappear!'}
onPress={() => hideHeader()}></Button>
</View>
);
};
export default withNavigation(Test);