React native: Изменить цвет выбранного элемента - PullRequest
1 голос
/ 29 апреля 2019

Моя навигация по ящикам - это навигация по стеку. Это означает, что я создал пользовательский ящик как навигацию по стеку, например:

class DrawerComponent extends React.Component {

  navigateToScreen = (route) => (
  () => {
    const navigateAction = NavigationActions.navigate({
      routeName: route
    });
    this.props.navigation.dispatch(navigateAction);
});


  render() {

    return (
          <ScrollView style={Styles.containerDrawer}>
            <View style={Styles.logoContainer}>
              <Image source={Images.logo}
                style={Styles.imageStyle}
                resizeMode={'contain'}
              />
            </View>

            <View style={Styles.blocksContainer}>
              <View style={Styles.firstBlock}>
                <TouchableOpacity
                  style={[Styles.buttonMenue, Styles.elevationButton, Styles.bgButton, Styles.centerContent]}
                  onPress= {this.navigateToScreen('Messages')}
                >
                  <IconMCI
                    name="message-text-outline" size={wp('10%')} color= '#000'
                    style={Styles.iconStyle}
                  />
                  <Text style={Styles.textButton}>الرسائل</Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={[Styles.buttonMenue, Styles.elevationButton, Styles.bgButton, Styles.centerContent]}
                  onPress= {this.navigateToScreen('Home')}
                >
                  <IconSI
                    name="home" size={wp('10%')} color= '#000'
                    style={Styles.iconStyle}
                  />
                  <Text style={Styles.textButton}>الإستقبال</Text>

                </TouchableOpacity>
              </View>

Моя проблема в том, что я не могу изменить стиль выбранного элемента.

это мой ящик, он выглядит так: enter image description here

Ответы [ 3 ]

0 голосов
/ 29 апреля 2019

this.props.activeItemKey в вашем методе render даст вам текущий ключ элемента, например Messages или Home в вашем случае ... вы можете использовать соответствующий стиль для активного элемента.

Секунда

Если возможно, переместите экраны, которые ваш StackNavigator отображает в routeConfigs, на ваш ящик вместо:

const DrawerNavigation = createDrawerNavigator({
  Home: { screen: HomeScreen },
  Screen2: { screen: StackScreen2 },
  Screen3: { screen: StackScreen3 },
});
0 голосов
/ 29 апреля 2019

это больше информации:

import React, {Component} from 'react';
import { createStackNavigator, createDrawerNavigator, createAppContainer } from 'react-navigation';
import HomeStackNavigation from './HomeStackNavigation'
import Messages from '../Components/Messages/Messages';
import DrawerComponent from '../Components/Drawer/Drawer';
import {Platform, Dimensions} from 'react-native';
// import ScoreList from '../Components/ScoreList/ScoreList';

var width = Dimensions.get('window').width;

const DrawerNavigation = createDrawerNavigator({
    Home: { // entree (route name) : on peut la nommer comme on veut mais on prefere lui donner le meme nom que notre screen qu'on va afficher
      screen: HomeStackNavigation, // le screen qu'on va afficher IL DOIT ETRE UN STACK
    },
},
{
  drawerWidth: width*0.83,
  contentComponent: props =>
  {
    return(<DrawerComponent  {...props}/>)
  },
  drawerPosition: 'left',
},
);

export default createAppContainer(DrawerNavigation)
0 голосов
/ 29 апреля 2019

Вы можете использовать состояния для обработки события клика для элемента и изменения класса на его основе, пример примера приведен ниже

    class DrawerComponent extends React.Component {

      state={
      clicked:true;
      }

      navigateToScreen = (route) => (
      () => {
        const navigateAction = NavigationActions.navigate({
          routeName: route
        });
        this.props.navigation.dispatch(navigateAction);
    });


      render() {

        return (
             ...

                <View style={Styles.blocksContainer}>
                  <View style={Styles.firstBlock}>
                    <TouchableOpacity
                      style={!this.state.clicked?[Styles.buttonMenue, Styles.elevationButton, Styles.bgButton, Styles.centerContent]:['custom-style']}
                      onPress= {()=>{
    this.setState({clicked:true})
    this.navigateToScreen('Messages')
    }}
                    >
 ...
                    </TouchableOpacity>

                  </View>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...