【问题标题】:How to show an image once a button has pressed in React native在 React Native 中按下按钮后如何显示图像
【发布时间】:2021-08-16 23:32:02
【问题描述】:

我有一个按钮,当你点击它时,它会调用一个函数,从 react.js 网站返回一个 Image 对象,但是当我点击按钮时图像没有显示。

这是我的代码:

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

export default function App() {

  function getImage() {
    return (
      <Image
      source={{
        uri: 'https://reactjs.org/logo-og.png',
        method: 'POST',
        headers: {
          Pragma: 'no-cache',
        },
        body: 'Your Body goes here',
      }}
      style={{width: 400, height: 400}}
    />
    )
  }

  return (
    <View style={styles.container}>
      <Button
        onPress={getImage}
        title="Click me"
        color="#841584"
      />
      
      <StatusBar style="auto" />
    </View>
  );
}

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

【问题讨论】:

    标签: react-native components


    【解决方案1】:

    好吧,你没有渲染任何东西...... 您可能应该做的是有一个状态来告知按钮是否被单击,并根据该状态决定是否要渲染图像而不是按钮?像这样的:

    import { StatusBar } from 'expo-status-bar';
    import React from 'react';
    import { StyleSheet, Text, View, Button, Image } from 'react-native';
    
    export default function App() {
      const [isShowingImage, setShowingImage] = React.useState(false)
    
      return (
        <View style={styles.container}>
          {
            isShowingImage ?
            (
             <Image
               source={{
               uri: 'https://reactjs.org/logo-og.png',
               method: 'POST',
               headers: {
                 Pragma: 'no-cache',
               },
                body: 'Your Body goes here',
               }}
               style={{width: 400, height: 400}}
              />
             ) : (
          <Button
            onPress={() => setShowingImage(true)}
            title="Click me"
            color="#841584"
          /> )
          }
          <StatusBar style="auto" />
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
      },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-11
      • 2017-01-25
      相关资源
      最近更新 更多