我使用react-navigation
作为我的导航解决方案。我需要在settings
屏幕上点击一个按钮来更改标签栏的背景颜色,但这样做会使所有屏幕重新渲染,这是现场演示:
正如您所看到的,每次按Change Tab Bar Background Color
屏幕中的Settings
按钮,标签栏的颜色都会发生变化,但同时,应用会自动导航到{{1屏幕出于某种原因。我使用Login
来维护当前主题,这里是代码:
行动创作者:
redux
减速机:
export function switchTheme() {
return { type: 'SWITCH_THEME' };
}
设置屏幕:
const INITIAL_STATE = {
backgroundColor: 'white'
};
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case 'SWITCH_THEME':
return { backgroundColor: state.backgroundColor === 'white' ? 'black' : 'white' };
default:
return state;
}
}
Main.js
import React, { Component } from 'react';
import { View, TouchableOpacity, Text } from 'react-native';
import { Icon } from 'react-native-elements';
import { connect } from 'react-redux';
import { switchTheme } from '../actions';
class SettingsScreen extends Component {
static navigationOptions = {
title: 'Settings',
header: null,
tabBarIcon: ({ tintColor }) => {
return (<Icon name='settings' size={30} color={tintColor} />);
}
};
render() {
return (
<View style={{ ... }}>
<TouchableOpacity
onPress={this.props.switchTheme}
style={{ ... }}
>
<Text style={{ ... }}>
Change Tab Bar Background Color
</Text>
</TouchableOpacity>
</View>
);
}
}
export default connect(null, { switchTheme })(SettingsScreen);
App.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { TabNavigator } from 'react-navigation';
import WelcomeScreen from './screens/WelcomeScreen';
import LoginScreen from './screens/LoginScreen';
import RegisterScreen from './screens/RegisterScreen';
import SettingsScreen from './screens/SettingsScreen';
import MessageScreen from './screens/MessageScreen';
class Main extends Component {
render() {
const MainTabNavigator = TabNavigator({
login: { screen: LoginScreen },
register: { screen: RegisterScreen },
message: { screen: MessageScreen },
setting: { screen: SettingsScreen }
}, {
tabBarOptions: {
style: { backgroundColor: this.props.backgroundColor }
}
});
return (
<MainTabNavigator />
);
}
}
const mapStateToProps = state => {
const { backgroundColor } = state.theme;
return { backgroundColor };
};
export default connect(mapStateToProps, null)(Main);
为什么应用导航到import React, { Component } from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Main from './Main';
class App extends Component {
render() {
return (
<Provider store={store}>
<Main />
</Provider>
);
}
}
export default App;
屏幕,我该怎么做以防止这种情况发生?
答案 0 :(得分:0)
在减速器SWITCH_THEME中更改backgroundcolor状态块 所以我认为当涉及到main.js并从state.theme中拉出backgroundColor时,prop backgroundColor会更新并重新呈现