javascript - 提升一个状态,以便我可以使用 onPress 对其进行修改

标签 javascript reactjs react-native react-state

我试图弄清楚提升状态是如何工作的。目前,我正在尝试在不同的组件中使用 onPress 来更改状态。在下面我提供的零食演示中,ListHomeMapHome出于某种原因不要回应,但你仍然会看到我想要完成的事情。
我想要 map 和列表“按钮”来完成“点击”的功能。
Demo - 当前实现没有错误,除了可触摸不透明度的闪光之外没有任何响应。 (还要记住零食由于某种原因没有响应。我的本地设备工作正常)
编辑:所以要清楚,我希望能够访问和更改状态 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();

最佳答案

您要实现的是一个常见用例,即更新祖先组件中的状态。你基本上有一个看起来像这样的组件树:
enter image description here
您正在尝试更新 Home 的状态来自 ListHome 的组件renderMap 的组件设置主屏幕状态的 Prop 。这是有道理的,所以你已经掌握了基本原理,它不起作用的原因是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方法做:

The bind() method creates a new function that, when called, has this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.


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

关于javascript - 提升一个状态,以便我可以使用 onPress 对其进行修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69157595/

相关文章:

javascript - JS 中的链式异步函数调用?

javascript - 如何从组件外部的 Redux 存储中获取值?

javascript - 渲染 div 的 map 及其标题

firebase - 如何修复此错误 "Function CollectionReference.doc()"

javascript - 加载路线时 ember-data 错误 : TypeError {}

javascript - Bootstrap 4下拉动画

javascript - 如何编写 eslint 时尚模式的配置文件?

react-native - 如何在卡片上添加 onPress 事件(在 native 基础上)?

javascript - 单击按钮时 Fancytree 激活节点

javascript - 组件输入错误