我正在为Dynamically App主题更改编写代码。当我从HomeScreen class
调用操作时,应用程序主题正在更改。但是我想更改App主题并从抽屉按钮中调用操作。
我想从抽屉按钮调用this.props.switchTheme()
。使用此按钮,我可以从“抽屉”按钮更改App主题。
请帮助我做到这一点。
it's my action.js
export const switchTheme = (BaseTheme) => {
return (dispatch) => {
dispatch({
type : 'SWITCH_THEME',
baseTheme : BaseTheme
});
};
};
it's my App.js
export default class App extends Component {
render() {
return (
<Provider store={store}>
<Container />
</Provider>
);
}
}
const AppStackNavigator = createStackNavigator({
Home : { screen: HomeScreen },
pro : {
screen : Profile
},
});
const customDrawerComponent = (props) => {
return (
<View>
<View
style={{
height : 60,
backgroundColor : '#437564',
alignItems : 'center',
justifyContent : 'center',
paddingVertical : 5
}}
/>
<ScrollView style={{ backgroundColor: '#fff' }}>
<DrawerNavigatorItems {...props} />
</ScrollView>
</View>
);
};
const DrawerNav = createDrawerNavigator(
{
Home : {
screen : AppStackNavigator
}
},
{
drawerPosition : 'left',
contentComponent : customDrawerComponent,
contentOptions : {
activeTintColor : '#4c8572',
inactiveTintColor : 'rgba(0,0,0,0.5)'
}
}
);
function mapStateToProps(state) {
return {
theme : state.themeReducer.theme
};
}
const Container = createAppContainer(DrawerNav);
it's is my HomeScreen
class HomeScreen extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerStyle : {
backgroundColor : '#4c8572'
},
headerLeft : (
<View style={{ paddingLeft: 10 }}>
<TouchableOpacity onPress={() => navigation.openDrawer()}>
<Text>Home</Text>
</TouchableOpacity>
</View>
),
headerTitleStyle : {
flex : 1,
color : '#fff',
alignItems : 'center',
justifyContent : 'center',
fontWeight : 'bold'
}
};
};
render() {
return (
<ThemeProvider theme={this.props.theme}>
<Container>
<TextContainer>
<Title>Change my theme</Title>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('pro')}
>
<Title>go to Profile</Title>
</TouchableOpacity>
</TextContainer>
{this.props.theme.mode === 'light' ? (
<Button onPress={() => this.props.switchTheme(darkTheme)}>
<ButtonText>Change to dark theme</ButtonText>
</Button>
) : (
<Button onPress={() => this.props.switchTheme(lightTheme)}>
<ButtonText>Change to light theme</ButtonText>
</Button>
)}
</Container>
</ThemeProvider>
);
}
}
function mapStateToProps(state) {
return {
theme : state.themeReducer.theme
};
}
export default connect(mapStateToProps, { switchTheme })(HomeScreen);
答案 0 :(得分:1)
我之前也遇到过同样的问题。您可以对抽屉做HomeScreeen的操作,即mapDispatchToProps。
使用以下代码简单地替换customDrawerComponent组件
const _customDrawerComponent = (props) => {
return (
<View>
<View
style={{
height : 60,
backgroundColor : '#437564',
alignItems : 'center',
justifyContent : 'center',
paddingVertical : 5
}}
/>
<ScrollView style={{ backgroundColor: '#fff' }}>
<DrawerNavigatorItems {...props} />
</ScrollView>
</View>
);
};
const customDrawerComponent = connect(null, { switchTheme }(_customDrawerComponent);