在 React Native 中使视图宽度为父级的 80% [英] Make view 80% width of parent in React Native

查看:21
本文介绍了在 React Native 中使视图宽度为父级的 80%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 React Native 中创建一个表单,并且想让我的 TextInput 占屏幕宽度的 80%.

使用 HTML 和普通 CSS,这将很简单:

输入{显示:块;宽度:80%;保证金:自动;}

除非 React Native 不支持 display 属性、百分比宽度或自动边距.

那我该怎么办呢?在 React Native 的问题跟踪器中有

  • 代码

    从'react'导入React;import { Text, View, StyleSheet } from 'react-native';const width_proportion = '80%';const height_proportion = '40%';const 样式 = StyleSheet.create({屏幕: {弹性:1,alignItems: '中心',justifyContent: '中心',背景颜色:'#5A9BD4',},盒子: {宽度:width_proportion,高度:height_proportion,alignItems: '中心',justifyContent: '中心',背景颜色:'#B8D2EC',},文本: {字体大小:18,},});导出默认值 () =>(<视图样式={styles.screen}><视图样式={styles.box}><文本样式={styles.text}>{width_proportion} 的宽度{'
    '}{height_proportion} 的高度</文本></查看></查看>);

  • I'm creating a form in React Native and would like to make my TextInputs 80% of the screen width.

    With HTML and ordinary CSS, this would be straightforward:

    input {
        display: block;
        width: 80%;
        margin: auto;
    }
    

    Except that React Native doesn't support the display property, percentage widths, or auto margins.

    So what should I do instead? There's some discussion of this problem in React Native's issue tracker, but the proposed solutions seem like nasty hacks.

    解决方案

    As of React Native 0.42 height: and width: accept percentages.

    Use width: 80% in your stylesheets and it just works.

    • Screenshot

    • Live Example
      Child Width/Height as Proportion of Parent

    • Code

      import React from 'react';
      import { Text, View, StyleSheet } from 'react-native';
      
      const width_proportion = '80%';
      const height_proportion = '40%';
      
      const styles = StyleSheet.create({
        screen: {
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#5A9BD4',
        },
        box: {
          width: width_proportion,
          height: height_proportion,
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#B8D2EC',
        },
        text: {
          fontSize: 18,
        },
      });
      
      export default () => (
        <View style={styles.screen}>
          <View style={styles.box}>
            <Text style={styles.text}>
              {width_proportion} of width{'
      '}
              {height_proportion} of height
            </Text>
          </View>
        </View>
      );
      

    这篇关于在 React Native 中使视图宽度为父级的 80%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆