React Native-单击按钮后更新文本

时间:2020-08-10 21:05:57

标签: react-native

我想在单击按钮后更新文本。

change text

但是找不到解决方法。

代码类似于:

import * as React from 'react';
import { View, Button, Text } from 'react-native';
import { NavigationContainer, CommonActions } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function HomeScreen({ navigation }) {
  const state = {
    user: 'test',
  };
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>{state.user}'s profile</Text>
      <Button
        title="Change user param"
        onPress={() =>
          navigation.dispatch({
            ...CommonActions.setParams({ user: 'Wojtek' }),
          })
        }
      />
    </View>
  );
}

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Expo example

我尝试过navigation.setParams()this.setState(),它们不能与我上面附加的代码一起使用。

1 个答案:

答案 0 :(得分:1)

您必须在功能组件中使用挂钩。因此,代码将如下所示:

import * as React from 'react';
import { View, Button, Text } from 'react-native';
import { NavigationContainer, CommonActions } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

function HomeScreen({ navigation }) {
  const [user, setUser] = React.useState('test');
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>{user}'s profile</Text>
      <Button
        title="Change user param"
        onPress={() => setUser("keidakira") }
      />
    </View>
  );
}

const Stack = createStackNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

检查它是否在Expo Link上正常工作