chr*_*zer 6 flexbox react-native
我想在我的界面中设置一个组件的样式.该组件必须具有至少200的宽度,但我想让它随着屏幕宽度增长到600.但是,有时人们使用平板电脑或大手机.而且我不希望该组件能够永远与屏幕一起成长.我希望它的最大宽度为600.
而且我知道maxWidth至少就目前来说还不是React Native中Flexbox实现的一部分......那么,今天有没有合理的方法呢?
您可以使用React Native 支持的maxWidth, maxHeight, minWidth,minHeight布局属性。
在此处记录React Native 布局道具。
例子:
StyleSheet.create({
container: {
maxWidth: '80%', // <-- Max width is 80%
minHeight: 20, // <-- Min height is 20
},
});
Run Code Online (Sandbox Code Playgroud)
React Native 中没有“maxWidth”这样的东西。您可能希望在运行时设置组件的样式。尝试使用Dimensions. 您可以获取设备的屏幕宽度和屏幕高度,并相应地调整组件的宽度。
您可以定义两个不同的样式对象。
对于宽度小于 600 的设备上的全宽组件。
componentStyle_1: {
flex: 1
}
Run Code Online (Sandbox Code Playgroud)
对于宽度大于 600 的设备上的 600 宽度
componentStyle_2: {
width: 600
}
Run Code Online (Sandbox Code Playgroud)
您可以检查设备宽度运行时。
var {height, width} = Dimensions.get('window');
if(width>600){
//load componentStyle_1
}
else{
//load componentStyle_2
}
Run Code Online (Sandbox Code Playgroud)
获得准确结果的最佳方法是使用您的代码。祝你好运!
参考: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...
Run Code Online (Sandbox Code Playgroud)
在类组件中,您将创建一个名为“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});
}
Run Code Online (Sandbox Code Playgroud)
在功能组件中,您将导入:
import React, { useEffect, useState } from "react";
Run Code Online (Sandbox Code Playgroud)
然后在你的功能组件中添加:
const [currentWidth, setCurrentWidth] = useState(null //or add in a default width);
useEffect(() => {
const currentWidth = Dimensions.get("screen").width;
setCurrentWidth({deviceWidth: currentWidth});
}, []);
Run Code Online (Sandbox Code Playgroud)
您还可以使用:
const deviceDisplay = Dimensions.get("window");
const deviceHeight = deviceDisplay.height;
const deviceWidth = deviceDisplay.width;
Run Code Online (Sandbox Code Playgroud)
..如果您也想找到高度。在 Android 上,“window”可获取包括上栏在内的全屏高度,而“screen”可获取不含上栏的高度。iOS 上的窗口和屏幕是相同的。
然后使用内联样式以便您可以访问状态,设置宽度和最大宽度:
<View style={[styles.wrapper, { width: this.state.deviceWidth, maxWidth: 400, // or whatever you want here. } ]} >
Run Code Online (Sandbox Code Playgroud)
在 StyleSheet 对象中找到的包装样式中的任何宽度设置都将被内联样式覆盖,就像在 CSS 中一样。
或者,如果您的 StyleSheet 对象中没有声明任何其他样式,则只需使用:
<View style={{ width: this.state.deviceWidth, maxWidth: 400 }} >
Run Code Online (Sandbox Code Playgroud)
或者在功能组件中,这将是:
<View style={{ width: deviceWidth, maxWidth: 400 }} >
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6527 次 |
| 最近记录: |