如何在React Native中使用vw和vh css

Dus*_*ler 4 css reactjs react-native

我正在使用React Native带有徽标和2个输入的基本登录名:

//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image } from 'react-native';

// create a component
class Login extends Component {
    render() {
        const imageURL = require('./images/CircleLogo.png');
        return (
            <View style={styles.container}>
                <View style={styles.loginContainer}>
                    <Image resizeMode="contain" style={styles.logo} source={imageURL} />
                </View>
                <View style={styles.formContainer}>
                    <LoginForm /> 
                </View>
            </View>
        );
    }
}

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'aliceblue',
    },
    loginContainer:{
        alignItems: 'center',
        flexGrow: 1,
        justifyContent: 'center'
    },
    logo: {
        position: 'absolute',
        width: '70vw',
        height: '70vw',
        maxWidth: 300
    }
});

//make this component available to the app
export default Login;
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用vwvhCSS测量。

这在网络上有效,但在iOS或Android上无效。

有人对处理vwvh测量有很好的建议吗?

边注:这似乎反应过来接受所看到的百分比在这里,我可以恢复。但是我的问题专门涉及vwvh测量。

Anu*_*lot 9

您可以在 react-native 中使用 Dimensions 而不是 veiwport。PFB 是 react-native Dimensions 的链接。

https://reactnative.dev/docs/dimensions

  • 这应该是公认的答案!无需添加额外的依赖项,它可以节省且轻松地依赖 React-natives 首选的“useWindowDimensions” API。自 v0.12.0 起,它将传播更新并与 react-native-web 无缝协作。 (3认同)

Bho*_*yar 8

我不知道 react-native 是否支持视口单位。但是,有一个模块:

https://www.npmjs.com/package/react-native-viewport-units

安装

npm install react-native-viewport-units --save
Run Code Online (Sandbox Code Playgroud)

用法

var {vw, vh, vmin, vmax} = require('react-native-viewport-units');
Run Code Online (Sandbox Code Playgroud)

注意所需的运算符/语法:x * vw

<View style={{height:50*vh, width:50*vw}}/>
var styles = StyleSheet.create({
  lookingGood: {
    width: 15*vmin,
    height: 10*vmax,
    padding: 2*vw,
    margin: 4*vh,
  }
});
Run Code Online (Sandbox Code Playgroud)


小智 6

视口单位:vw,vh,vmin,vmax-React Native。

https://github.com/joetakara/react-native-expo-viewport-units

安装

npm install react-native-expo-viewport-units
Run Code Online (Sandbox Code Playgroud)

要么

yarn add react-native-expo-viewport-units
Run Code Online (Sandbox Code Playgroud)

用法

import { vw, vh, vmin, vmax } from 'react-native-expo-viewport-units';

<View style={{ width: vw(100), height: vh(100) }}>
  ...
<View>
Run Code Online (Sandbox Code Playgroud)