我想为我的界面中的一个组件设置样式。该组件的宽度必须至少为200,但是我希望它能随着屏幕宽度增加而增加,最多可达到600。不过,有时人们会使用平板电脑或大型手机。我不希望组件能够随着屏幕无限制地增长。我希望它具有最大宽度为600。
我知道在React Native中的flexbox实现中,maxWidth目前尚未成为实际存在的一种属性... 那么,今天是否有合理的方法可以解决这个问题呢?
我想为我的界面中的一个组件设置样式。该组件的宽度必须至少为200,但是我希望它能随着屏幕宽度增加而增加,最多可达到600。不过,有时人们会使用平板电脑或大型手机。我不希望组件能够随着屏幕无限制地增长。我希望它具有最大宽度为600。
我知道在React Native中的flexbox实现中,maxWidth目前尚未成为实际存在的一种属性... 那么,今天是否有合理的方法可以解决这个问题呢?
maxWidth
,maxHeight
,minWidth
和minHeight
布局属性。StyleSheet.create({
container: {
maxWidth: '80%', // <-- Max width is 80%
minHeight: 20, // <-- Min height is 20
},
});
Dimensions
。您可以获取设备的屏幕宽度和高度,并相应地调整组件的宽度。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...
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上的Window和Screen是相同的。
然后使用内联样式,以便您可以访问状态,设置宽度和最大宽度:
<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 }} >