React Native图像会占用所有可用的垂直空间

时间:2019-07-05 09:14:23

标签: android react-native layout react-native-android

我是本机反应的新手(两天前开始),但是我很快就选择了它,因为我已经知道了常规反应。我正在尝试编写一个现实世界的应用程序,但无法弄清楚如何正确放置图像,我想让Image标签占据屏幕上的所有水平空间,但我也希望它保持在最顶部屏幕并保持其宽高比(我无法进行硬编码,因为我还将显示其他车牌图片,包括北美地区不是2/1的欧洲车牌),同时都不会占用实际的图像所有可用的垂直空间。

这是我的代码呈现的内容和我实际想要的内容的GIMP编辑: https://ibb.co/XJgrhkC

这是我的渲染功能:

export default class App extends Component {
  ...

  render() {
    return (
      <View style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}>
        <Image
          source={require(`./resources/images/north_america/original/alaska.jpg`)}
          style={{ flex: 1, width: screenWidth }}
          resizeMode="contain" />
        <Button title="Random state" onPress={this.getRandomState} />
      </View>
    );
  }
}

我熟悉css的布局选项,但是react-native似乎有所不同,我无法将宽度,flex和resizeModes的所有组合都包裹住。

2 个答案:

答案 0 :(得分:1)

通常,将flex应用于<View /><Image />的{​​{1}}标记时,父组件的子代将具有相同的<Button />道具应用。因此,您可以删除flex下的flex道具。

在本机处理<Image />已有一段时间,我必须说为<Image />height指定值对于显示width很重要正确地

您可以在我的Expo示例here上进行尝试。

<Image />

此外,由于您是本机反应的新手,我是否建议您将 render() { return ( <View style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}> <Image source={require(`./resources/images/north_america/original/alaska.jpg`)} style={{ width: screenWidth, height: 200, }} resizeMode="contain" /> <Button title="Random state" onPress={this.getRandomState} /> </View> ); } 更改为<Button />?当用户在移动设备上按下它时,它会提供视觉帮助。

答案 1 :(得分:0)

使用flex时,添加{borderWidth:2,borderColor:'red'}时,图像会自动占据大量空间。相反,您必须手动指定高度。如果您希望它正确缩放,可以尝试以下操作:

import React from "react";
import { View, Image, Button, Dimensions } from "react-native";

class App extends React.Component {
  state = {
    imgWidth: 0,
    imgHeight: 0
  };

  componentDidMount() {
    Image.getSize("https://i.ibb.co/HgsfWpH/sc128.jpg", (width, height) => {
      // Calculate image width and height
      const screenWidth = Dimensions.get("window").width;
      const scaleFactor = width / screenWidth;
      const imageHeight = height / scaleFactor;
      this.setState({ imgWidth: screenWidth, imgHeight: imageHeight });
    });
  }
  render() {
    return (
      <View
        style={{ flex: 1, justifyContent: "flex-start", alignItems: "center" }}
      >
        <Image
          style={{
            flex: 1,
            width: Dimensions.get("window").width,
            borderColor: "red",
            borderWidth: 2
          }}
          source={{
            uri: "https://i.ibb.co/HgsfWpH/sc128.jpg"
          }}
          resizeMode="contain"
        />
        <Button title="Random state" onPress={this.getRandomState} />
      </View>
    );
  }
}

export default App;