简体   繁体   中英

React Native show two views simultaneously

I'm very new to working with react native, before I only used Java. My Problem is, that my app doesn't show the second View:

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableHighlight } from 'react-native';

This puts Hello World on the screen, and when you press it, it calls displayImage:

export default function App() {


  return (
    <SafeAreaView style={styles.container}>
      <Text numberOfLines={1}
        onPress={displayImage}>
        HELLO WORLD</Text>
    </SafeAreaView>
  );
}

This is the function, that should display the image below the Hello World but it doesn't, when both are in the same View it works.

function displayImage() {
  console.log("Imagefunction is called");
  return (
    //This should be displayed when pressing Hello World
    <SafeAreaView style={styles.container} >
      <TouchableHighlight onPress={() => console.log("Image clicked")} >
        <Image
          source={{
            width: 200,
            height: 300,
            uri: "https://picsum.photos/200/300"
          }} />
      </TouchableHighlight>
    </SafeAreaView >
  )

}

This is just the style:

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: "center",
    justifyContent: "center",

  },


});

You can't return a component like this, instead you should control the visibility of the component via state like this:

import React, {useState} from 'react';

export default function App() {

  const [imageVisible, setImageVisible] = useState(false);

  function displayImage() {
    setImageVisible(true);
  }

  return (
    <SafeAreaView style={styles.container}>
      <Text numberOfLines={1}
        onPress={displayImage}>
        HELLO WORLD</Text>
      {imageVisible && <TouchableHighlight onPress={() => console.log("Image clicked")} >
        <Image
          source={{
            width: 200,
            height: 300,
            uri: "https://picsum.photos/200/300"
          }} />
      </TouchableHighlight>}
    </SafeAreaView>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM