首页 > 解决方案 > 提升一个状态,以便我可以使用 onPress 对其进行修改

问题描述

我试图弄清楚提升状态是如何工作的。目前,我正在尝试在不同的组件中使用 onPress 来更改状态。在下面我提供的零食演示中,ListHome由于MapHome某种原因没有响应,但您仍然会看到我正在尝试完成的工作。

我想要地图和列表“按钮”来完成“点击”的功能。

演示- 当前实现没有错误,除了可触摸不透明度的闪光之外没有任何响应。(还记得零食由于某种原因没有响应。我的本地设备工作正常)

编辑:所以要清楚,我希望能够whichComponentToShow从另一个组件访问和更改状态。即ListHome组件。

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true,
      whichComponentToShow: 'Screen1',
    };
  }

  goToMap = () => {
    this.setState({ whichComponentToShow: 'Screen2' });
  };

  render(){
    if(this.state.whichComponentToShow === 'Screen1'){
      return(
       <View style={{backgroundColor: '#d1cfcf' ,flex: 1}}>
        
        <ListHome
          renderMap = {this.goToMap.bind(this)}
        />
  }
}
export default class ListHome extends React.Component {
  
goToMap = () => {
  this.props.renderMap();
}

<TouchableOpacity onPress={() => this.goToMap.bind(this)}>
     <View style={styles.conditionalMap}>   
         <View style={{justifyContent: 'center', alignItems: 'center'}}>       
             <Text style={{color: 'black', fontSize: scale(15)}}>
                 Map
             </Text>                  
         </View>
     </View>
</TouchableOpacity>
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { MaterialCommunityIcons } from '@expo/vector-icons';

import VenueDetailsScreen from './screens/VenueDetails';
import CarouselGallary from './screens/Carousel';
import Home from './screens/Home';
import Friends from './screens/Friends';
import Profile from './screens/Profile';

const Tab = createBottomTabNavigator();

function MyTabs() {
  return (
    <Stack.Navigator initialRouteName="Home">
      <Stack.Screen
        name="Home"
        component={Home}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="VenueDetails"
        component={VenueDetailsScreen}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="CarouselGallary"
        component={CarouselGallary}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Friends"
        component={Friends}
        options={{ headerShown: false }}
      />
      <Stack.Screen
        name="Profile"
        component={Profile}
        options={{ headerShown: false }}
      />
    </Stack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName="Home"
        screenOptions={{
          tabBarActiveTintColor: '#F60081',
          tabBarInactiveTintColor: '#4d4d4d',
          tabBarStyle: {
            backgroundColor: '#d1cfcf',
            borderTopColor: 'transparent',
          },
        }}>
        <Tab.Screen
          name="Home"
          component={MyTabs}
          options={{
            tabBarLabel: 'Home',
            headerShown: false,
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons name="home" color={color} size={size} />
            ),
          }}
        />
        <Tab.Screen
          name="Friends"
          component={Friends}
          options={{
            tabBarLabel: 'Friends',
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="account-group"
                color={color}
                size={size}
              />
            ),
          }}
        />
        <Tab.Screen
          name="Profile"
          component={Profile}
          options={{
            tabBarLabel: 'Profile',
            tabBarIcon: ({ color, size }) => (
              <MaterialCommunityIcons
                name="account"
                color={color}
                size={size}
              />
            ),
          }}
        />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

const Stack = createStackNavigator();

标签: javascriptreactjsreact-nativereact-state

解决方案


您要实现的是一个常见用例,即更新祖先组件中的状态。你基本上有一个看起来像这样的组件树:

在此处输入图像描述

您正在尝试使用设置主屏幕状态的道具HomeListHome组件更新组件的状态。renderMap这是有道理的,所以你有基本的原则,它不工作的原因是由于ListHome组件中的一个小错误

<View style={styles.conditionalMap}>
  <TouchableOpacity onPress={() => this.goToMap.bind(this)}>
    // In the above line, change to this.goToMap()

    <View style={{ justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ color: 'black', fontSize: scale(15) }}>Map</Text>
    </View>
  </TouchableOpacity>
</View>

这就是bind方法的作用:

bind() 方法创建一个新函数,在调用该函数时,将 this 关键字设置为提供的值,并在调用新函数时提供的任何参数之前具有给定的参数序列。

因此,onPress当前定义的方式是,它将创建一个新函数,但该函数从未实际调用过。更改this.goToMap.bind(this)this.goToMap()应该可以解决您的问题。


推荐阅读