无法传递参数反应本机5.x

时间:2020-10-16 12:30:37

标签: javascript android react-native

我不知道为什么,但是程序stats.js无法读取SearchScreen.js传递的参数 谁能帮我吗?

SearchScreen.js

const SearchScreen =({navigation}) => {
const [name, SetName] = React.useState();
    return (
        <View style={styles.container}>
        <TextInput
                    style={styles.inputText}
                    placeholder="Name of the restaurant..."
                    placeholderTextColor="#003f5c"
                    onChangeText={text => SetName(text)}
                    //onSubmitEditing={ () => this.state.navigate('InsertEmailAddress', name)}
                    />
                    <Text> {name} </Text>
                    <TouchableOpacity
                   onPress={() => {navigation.setParams(name), navigation.navigate('Stats', name)}}>
                  <Text >continue</Text>
                </TouchableOpacity>
        </View>
    );
};

Stats.js

const StatsScreen = ({route, navigation}) => {
    return (
        <View style={styles.container}>
            <Text> Stats Screen </Text>
              <Text>{route.params}</Text>
        </View>
    );
};

2 个答案:

答案 0 :(得分:0)

尝试一下

navigation.navigate('Stats',{name});

尝试使用默认值初始化

const [name, SetName] = React.useState("");

答案 1 :(得分:0)

如果您使用这样的路线设计了堆栈导航器

const Stack = createStackNavigator();

<Stack.Navigator>
  <Stack.Screen name="SearchScreen" component={SearchScreen} />
  <Stack.Screen name="Stats" component={StatsScreen} />
</Stack.Navigator>

这将从第一个屏幕到第二个屏幕获取参数。如果两个屏幕都属于同一堆栈

const SearchScreen = ({ navigation }) => {
  const [name, SetName] = React.useState('');
  return (
    <View style={styles.container}>
      <TextInput
        value={name}
        style={styles.inputText}
        placeholder="Name of the restaurant..."
        placeholderTextColor="#003f5c"
        onChangeText={(text) => SetName(text)}
        //onSubmitEditing={ () => this.state.navigate('InsertEmailAddress', name)}
      />
      <Text> {name} </Text>
      <TouchableOpacity
        onPress={() => {
          navigation.navigate('Stats', name);
        }}>
        <Text>continue</Text>
      </TouchableOpacity>
    </View>
  );
};
const StatsScreen = ({ route, navigation }) => {
  return (
    <View style={styles.container}>
      <Text> Stats Screen </Text>
      <Text>{route.params}</Text>
    </View>
  );
};

如果您有一个嵌套的导航器,则在传递参数时会有slight difference,其余所有内容都保持不变。