【问题标题】:Make dimension relative to another in React Native在 React Native 中制作相对于另一个维度的维度
【发布时间】:2018-02-28 10:24:21
【问题描述】:

问题

我正在使用 React Native 开发一个应用程序,我需要一个图像,即它的高度是宽度的某个百分比。

代码

在图片中,背景是一个Image,里面有另一个Image。我正在使用样式化组件。

export const ImageWithButtonStyled = styled.TouchableOpacity`
  padding: ${Spacing.XLarge}
  alignItems: center
  width: 50%
`;

export const ImageWithButtonImageContentStyled = styled.View`
`;

export const ImageWithButtonBackgroundStyled = styled.Image`
  marginLeft: ${Spacing.Large}
  marginRight: ${Spacing.Large}
  backgroundColor: ${Color.GrayLight}
  borderWidth: 1
  borderColor: ${Color.Gray}
  justifyContent: center
  alignItems: center
  width: 100%
`;

export const ImageWithButtonButtonContentStyled = styled.View`
 alignSelf: stretch
 alignContent: center
`;

这是它们在组件render() 方法中的使用方式:

  render() {
    return (
      <ImageWithButtonStyled>
        <ImageWithButtonBackgroundStyled source={null}>
          <Image source={require('../assets/ic_photo/ic_photo.png')}/>
        </ImageWithButtonBackgroundStyled>
        <ImageWithButtonButtonContentStyled>
          <LinkButton text={this.props.buttonText} />
        </ImageWithButtonButtonContentStyled>
      </ImageWithButtonStyled>
    );
  }

我在寻找什么

我要找的结果是这样的:

但不必硬编码任何尺寸,只需使用百分比并将高度设置为宽度的百分比,以便灰色框在任何屏幕中保持我定义的纵横比,相应地缩放。所以,如果我说高度是宽度的 1.4,那么这个方面将在任何屏幕中保持。

非常感谢任何帮助,谢谢。

【问题讨论】:

标签: image layout react-native


【解决方案1】:

因为react-native 中的宽度和高度值是无单位的,并且您不能使用width: 50% 之类的值,所以您应该在应用程序中使用Dimension。您可以使用下面的代码获取屏幕的尺寸,并使用 width: width/2 之类的方式设置组件的样式

import {Dimensions} from 'react-native'
...
let {height, width} = Dimensions.get('window')

【讨论】:

  • 事实是,% 并不是一个真正的单位,而是缺少,不是吗?因为它是(单位)/(单位)。也许这就是它一直在起作用的原因。只要您的解决方案有效,我想直接在样式中设置它,否则,我会将样式传递给组件类,这是我想避免的。但是,如果没有其他解决方案...
  • 你可以在任何你想要的地方使用这个Dimension,在style 属性或StyleSheet 对象中。当然我应该说,制作布局和样式的最佳方法是使用Flex。您可以阅读此链接了解更多信息:facebook.github.io/react-native/docs/height-and-width.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-12-16
相关资源
最近更新 更多