【问题标题】:React native image full width not working with `alignItems: 'center'`反应原生图像全宽不适用于`alignItems:'center'`
【发布时间】:2016-09-22 02:17:45
【问题描述】:

您好,我正在处理一个 react-native 项目。我正在尝试将图像的宽度设置为屏幕的整个宽度。基于各种stackoverflow答案和this github issue我写了以下代码

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
    alignSelf: 'stretch'
  },
  canvas: {
    flex: 1,
    width: null,
    height: null
  },
});

return (
    <View style={styles.container}>
      <Image
        resizeMode="cover"
        source={pic}
        style={styles.canvas} />
    </View>        
);

但是,当我在样式规则容器中添加以下规则 alignItems: 'center' 时。图片不再渲染。我想知道为什么alignItems: 'center' 阻止图片渲染?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    alignItems: 'center' 没有预先确定的width/height,因此您必须在画布样式规则中指定width/height,或者在相同的规则中放置alignSelf: 'stretch'

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        backgroundColor: '#F5FCFF',
        alignSelf: 'stretch',
      },
      canvas: {
        flex: 1,
        alignSelf: 'stretch',
        width: null,
        height: null
      },
    });
    

    【讨论】:

    • 这对我来说完全有用,尽管我删除了 null 的宽度/高度,因为它根本无法显示图像(react-native v0.40)
    【解决方案2】:

    您可以使用Dimensions获取窗口的宽度和高度,参见以下示例

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

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 2020-07-31
      • 2018-09-18
      • 2019-02-28
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 2021-12-10
      相关资源
      最近更新 更多