React Native如何做最小/最大宽度

时间:2016-03-29 20:51:48

标签: react-native flexbox

我想在界面中设置一个组件的样式。该组件必须具有至少200的宽度,但我想让它随着屏幕宽度增长到600.但是,有时人们使用平板电脑或大手机。而且我不希望该组件能够永远与屏幕一起成长。我希望它的最大宽度为600。

而且我知道maxWidth至少就目前来说还不是React Native中的flexbox实现的一部分...所以,今天有合理的方法吗?

4 个答案:

答案 0 :(得分:6)

您可以使用React Native支持的maxWidthmaxHeightminWidthminHeight布局属性。

React Native layout props这里记录

示例:

StyleSheet.create({
  container: {
    maxWidth: '80%',   // <-- Max width is 80%
    minHeight: 20,     // <-- Min height is 20
  },
});

答案 1 :(得分:1)

React Native中没有“maxWidth”这样的东西。您可能希望在运行时设置组件的样式。尝试使用Dimensions。您可以获得设备的屏幕宽度和屏幕高度,并相应地调整组件的宽度。

您可以定义两个不同的样式对象。

对于宽度小于600的设备上的全宽组件。

componentStyle_1: {
    flex: 1
}

对于宽度大于600的设备上的600宽度

componentStyle_2: {
    width: 600
}

您可以检查设备宽度运行时间。

var {height, width} = Dimensions.get('window');

if(width>600){
    //load componentStyle_1
}
else{
    //load componentStyle_2
}

获得准确结果的最佳方法是使用您的代码。祝你好运!

参考:https://facebook.github.io/react-native/docs/dimensions.html#content

答案 2 :(得分:0)

您可以使用辅助类PixelRatio。

https://facebook.github.io/react-native/docs/pixelratio.html

答案 3 :(得分:0)

简单。只需在样式中使用maxWidth即可。

以实用的方式,这是您的使用方式:

   import { StyleSheet, Text, View, Dimensions, (+ anything else you need such as Platform to target specific device widths } from "react-native";
   // plus whatever other imports you need for your project...

在类组件中,您将创建一个状态,该状态称为any,比如deviceWidth。然后在组件内部使用:

constructor(props) {
    super(props);
    this.state = {
      deviceWidth: 375, // Put in any default size here or just "null"
      // plus any other state keys you need in your project
      }

componentDidMount() {
  const currentWidth = Dimensions.get("screen").width;
  this.setState({deviceWidth: currentWidth});
}

在功能组件中,您将导入:

  import React, { useEffect, useState } from "react";

然后在功能组件内部添加:

  const [currentWidth, setCurrentWidth] = useState(null //or add in a default width);

  useEffect(() => {
    const currentWidth = Dimensions.get("screen").width;
    setCurrentWidth({deviceWidth: currentWidth});
  }, []);

您还可以使用:

 const deviceDisplay = Dimensions.get("window");
 const deviceHeight = deviceDisplay.height;
 const deviceWidth = deviceDisplay.width;

..如果您也想查找高度。在Android上,“窗口”可让您获得包括上栏在内的全屏高度,而“屏幕”可让您获得没有上栏的高度。 iOS上的窗口和屏幕是相同的。

然后使用内联样式,以便您可以访问状态,设置width和maxWidth:

   <View style={[styles.wrapper, { width: this.state.deviceWidth,  maxWidth: 400, // or whatever you want here. } ]} >

就像在CSS中一样,在StyleSheet对象中找到的任何包装样式中的宽度设置都将被内联样式覆盖。

或者,如果您没有在StyleSheet对象中声明任何其他样式,则只需使用:

  <View style={{ width: this.state.deviceWidth,  maxWidth: 400 }} >

或者在功能组件中,应该是:

  <View style={{ width: deviceWidth,  maxWidth: 400 }} >