【发布时间】:2020-02-15 04:10:01
【问题描述】:
我想在我的界面中设置一个组件的样式。组件的宽度必须至少为 200,但我想让它随着屏幕宽度增长到 600。但是,有时人们使用平板电脑或大型手机。而且我不希望组件能够永远与屏幕一起增长。我希望它的最大宽度为 600。
而且我知道 maxWidth 至少目前不是 React Native 中弹性盒实现的一部分……那么,今天有没有合理的方法来做到这一点?
【问题讨论】:
标签: react-native flexbox
我想在我的界面中设置一个组件的样式。组件的宽度必须至少为 200,但我想让它随着屏幕宽度增长到 600。但是,有时人们使用平板电脑或大型手机。而且我不希望组件能够永远与屏幕一起增长。我希望它的最大宽度为 600。
而且我知道 maxWidth 至少目前不是 React Native 中弹性盒实现的一部分……那么,今天有没有合理的方法来做到这一点?
【问题讨论】:
标签: react-native flexbox
您可以使用 React Native 支持的 maxWidth、maxHeight、minWidth、minHeight 布局属性。
在此处记录React Native layout props。
例子:
StyleSheet.create({
container: {
maxWidth: '80%', // <-- Max width is 80%
minHeight: 20, // <-- Min height is 20
},
});
【讨论】:
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
【讨论】:
简单。只需在您的样式中使用 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...
在类组件中,您将创建一个名为“whatever”的状态,比如说 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 上,“window”为您提供包括上栏在内的全屏高度,而“screen”为您提供不带上栏的高度。 iOS 上的窗口和屏幕是一样的。
然后使用内联样式以便您可以访问状态,设置宽度和最大宽度:
<View style={[styles.wrapper, { width: this.state.deviceWidth, maxWidth: 400, // or whatever you want here. } ]} >
在您的 StyleSheet 对象中找到的包装样式中的任何宽度设置都将被内联样式覆盖,就像在 CSS 中一样。
或者,如果您没有在 StyleSheet 对象中声明任何其他样式,则只需使用:
<View style={{ width: this.state.deviceWidth, maxWidth: 400 }} >
或者在一个功能组件中,那就是:
<View style={{ width: deviceWidth, maxWidth: 400 }} >
【讨论】: