【问题标题】:Make view 80% width of parent in React Native在 React Native 中使视图宽度为父级的 80%
【发布时间】:2016-02-29 15:04:35
【问题描述】:

我正在 React Native 中创建一个表单,并希望将我的 TextInputs 设置为屏幕宽度的 80%。

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

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

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

那么我应该怎么做呢?在 React Native 的问题跟踪器中有 some discussion of this problem,但建议的解决方案看起来像是讨厌的 hack。

【问题讨论】:

  • react-native 使用flex 表示元素的大小和位置。我不确定,但可能flex-basis 是您需要的:检查thisthis
  • 根据this issueflex: 0.8 之类的东西可能会起作用。

标签: javascript css reactjs react-native


【解决方案1】:

从 React Native 0.42 height:width: 开始接受百分比。

在您的样式表中使用width: 80% 就可以了。

  • 截图

  • 现场示例
    Child Width/Height as Proportion of Parent

  • 代码

    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{'\n'}
            {height_proportion} of height
          </Text>
        </View>
      </View>
    );
    

【讨论】:

    【解决方案2】:

    这应该符合您的需求:

    var yourComponent = React.createClass({
        render: function () {
            return (
                <View style={{flex:1, flexDirection:'column', justifyContent:'center'}}>
                    <View style={{flexDirection:'row'}}>
                        <TextInput style={{flex:0.8, borderWidth:1, height:20}}></TextInput>
                        <View style={{flex:0.2}}></View> // spacer
                    </View>
                </View>
            );
        }
    });
    

    【讨论】:

    • 只是
    【解决方案3】:

    如果您只是想让输入相对于屏幕宽度,一种简单的方法是使用尺寸:

    // De structure Dimensions from React
    var React = require('react-native');
    var {
      ...
      Dimensions
    } = React; 
    
    // Store width in variable
    var width = Dimensions.get('window').width; 
    
    // Use width variable in style declaration
    <TextInput style={{ width: width * .8 }} />
    

    我已经建立了一个工作项目here。代码也在下面。

    https://rnplay.org/apps/rqQPCQ

    'use strict';
    
    var React = require('react-native');
    var {
      AppRegistry,
      StyleSheet,
      Text,
      View,
      TextInput,
      Dimensions
    } = React;
    
    var width = Dimensions.get('window').width;
    
    var SampleApp = React.createClass({
      render: function() {
        return (
          <View style={styles.container}>
            <Text style={{fontSize:22}}>Percentage Width In React Native</Text>
            <View style={{marginTop:100, flexDirection: 'row',justifyContent: 'center'}}>
                <TextInput style={{backgroundColor: '#dddddd', height: 60, width: width*.8 }} />
              </View>
          </View>
        );
      }
    });
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
        marginTop:100
      },
    
    });
    
    AppRegistry.registerComponent('SampleApp', () => SampleApp);
    

    【讨论】:

    • React Native 文档应该在首页上提到Dimensions 包——这并不让我吃惊...
    • 非常有价值的答案。维度实际上非常有用。注意:“尽管尺寸立即可用,但它们可能会发生变化(例如,由于设备旋转),因此任何依赖于这些常量的渲染逻辑或样式都应尝试在每次渲染时调用此函数,而不是缓存值(例如,使用内联样式,而不是在样式表中设置值)。”
    • 请注意,如果您支持横向并且不手动处理这些布局更改,则使用尺寸会破坏您的布局后屏幕旋转。
    【解决方案4】:

    在您的样式表中,简单地说:

    width: '80%';
    

    代替:

    width: 80%;
    

    继续编码...... :)

    【讨论】:

    【解决方案5】:

    你也可以试试react-native-extended-stylesheet,它支持单向应用的百分比:

    import EStyleSheet from 'react-native-extended-stylesheet';
    
    const styles = EStyleSheet.create({
      column: {
        width: '80%',
        height: '50%',
        marginLeft: '10%'
      }
    });
    

    【讨论】:

      【解决方案6】:

      我用来获得父级宽度百分比的技术是添加一个额外的间隔视图和一些弹性框。这并不适用于所有场景,但非常有用。

      所以我们开始:

      class PercentageWidth extends Component {
          render() {
              return (
                  <View style={styles.container}>
                      <View style={styles.percentageWidthView}>
                          {/* Some content */}
                      </View>
      
                      <View style={styles.spacer}
                      </View>
                  </View>
              );
          }
      }
      
      const styles = StyleSheet.create({
          container: {
              flexDirection: 'row'
          },
      
          percentageWidthView: {
              flex: 60
          },
      
          spacer: {
              flex: 40
          }
      });
      

      基本上,flex 属性是相对于 flex 容器中所有项目的“总”flex 的宽度。因此,如果所有项目总和为 100,则您有一个百分比。在示例中,我可以使用 flex 值 6 和 4 来获得相同的结果,因此它更加灵活。

      如果要将百分比宽度视图居中:添加两个宽度为一半的垫片。所以在这个例子中它将是 2-6-2。

      当然,添加额外的视图并不是世界上最好的事情,但在现实世界的应用程序中,我可以想象间隔将包含不同的内容。

      【讨论】:

      • 你能想象spacer会包含不同的内容吗?为什么?我可以想到很多例子,其中间隔符只是填充 html。
      【解决方案7】:

      我有一个更新的解决方案(2019 年末),以获得 80% 的父级宽度使用 Hooks 响应即使设备旋转也能正常工作。

      您可以在此示例中使用Dimensions.get('window').width 获取设备宽度,您可以了解如何响应式地做到这一点

      import React, { useEffect, useState } from 'react';
      import { Dimensions , View , Text , StyleSheet  } from 'react-native';
      
      export default const AwesomeProject() => {
         const [screenData, setScreenData] = useState(Dimensions.get('window').width);
      
          useEffect(() => {
           const onChange = () => {
           setScreenData(Dimensions.get('window').width);
           };
           Dimensions.addEventListener('change', onChange);
      
           return () => {Dimensions.removeEventListener('change', onChange);};
          });
      
         return (  
                <View style={[styles.container, { width: screenData * 0.8 }]}>
                   <Text> I'mAwesome </Text>
                 </View>
          );
      }
      
      const styles = StyleSheet.create({
      container: {
           flex: 1,
           alignItems: 'center',
           justifyContent: 'center',
           backgroundColor: '#eee',
           },
      });
      

      【讨论】:

        【解决方案8】:

        这就是我得到解决方案的方式。简单而甜蜜。与屏幕密度无关:

        export default class AwesomeProject extends Component {
            constructor(props){
                super(props);
                this.state = {text: ""}
            }
          render() {
            return (
               <View
                  style={{
                    flex: 1,
                    backgroundColor: "#ececec",
                    flexDirection: "column",
                    justifyContent: "center",
                    alignItems: "center"
                  }}
                >
                  <View style={{ padding: 10, flexDirection: "row" }}>
                    <TextInput
                      style={{ flex: 0.8, height: 40, borderWidth: 1 }}
                      onChangeText={text => this.setState({ text })}
                      placeholder="Text 1"
                      value={this.state.text}
                    />
                  </View>
                  <View style={{ padding: 10, flexDirection: "row" }}>
                    <TextInput
                      style={{ flex: 0.8, height: 40, borderWidth: 1 }}
                      onChangeText={text => this.setState({ text })}
                      placeholder="Text 2"
                      value={this.state.text}
                    />
                  </View>
                  <View style={{ padding: 10, flexDirection: "row" }}>
                    <Button
                      onPress={onButtonPress}
                      title="Press Me"
                      accessibilityLabel="See an Information"
                    />
                  </View>
                </View>
            );
          }
        }
        

        【讨论】:

          【解决方案9】:

          最简单的实现方法是对视图应用宽度。

          width: '80%'
          

          【讨论】:

            【解决方案10】:

            只需在代码中为大小添加引号即可。使用它,您可以使用宽度、高度的百分比

            input: {
                width: '80%'
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-02-18
              • 2021-12-13
              • 2017-06-13
              • 2021-05-13
              • 1970-01-01
              • 2020-11-04
              相关资源
              最近更新 更多