Javascript 使React中的视图宽度为父视图的80%

Javascript 使React中的视图宽度为父视图的80%,javascript,css,reactjs,react-native,Javascript,Css,Reactjs,React Native,我正在React Native中创建一个表单,希望将我的TextInputs设置为屏幕宽度的80% 使用HTML和普通CSS,这将非常简单: input { display: block; width: 80%; margin: auto; } 除此之外,React Native不支持显示属性、宽度百分比或自动边距 那么我应该怎么做呢?React Native的问题跟踪器中有一些问题,但提出的解决方案看起来像是令人讨厌的黑客。如果您只是想让输入相对于屏幕宽度,一个简单的

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

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

input {
    display: block;
    width: 80%;
    margin: auto;
}
除此之外,React Native不支持显示属性、宽度百分比或自动边距


那么我应该怎么做呢?React Native的问题跟踪器中有一些问题,但提出的解决方案看起来像是令人讨厌的黑客。

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

// 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 }} />
//从React中取消结构维度
var React=require('React-native');
变量{
...
尺寸
}=反应;
//在变量中存储宽度
var width=Dimensions.get('window').width;
//在样式声明中使用宽度变量
我已经建立了一个工作项目。代码也在下面

“严格使用”;
var React=require('React-native');
变量{
评估学,
样式表,
文本,
看法
文本输入,
尺寸
}=反应;
var width=Dimensions.get('window').width;
var SampleApp=React.createClass({
render:function(){
返回(
反应本机的宽度百分比
);
}
});
var styles=StyleSheet.create({
容器:{
弹性:1,
玛金托普:100
},
});
AppRegistry.registerComponent('SampleApp',()=>SampleApp);

适合您的需要:

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>
        );
    }
});
var yourComponent=React.createClass({
渲染:函数(){
返回(
//间隔棒
);
}
});
您还可以尝试支持单方向应用程序的百分比:

import EStyleSheet from 'react-native-extended-stylesheet';

const styles = EStyleSheet.create({
  column: {
    width: '80%',
    height: '50%',
    marginLeft: '10%'
  }
});

我用于获得父对象的百分比宽度的技术是添加一个额外的间隔视图,并结合一些flexbox。这并不适用于所有场景,但可能非常有用

现在我们开始:

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
    }
});
class PercentageWidth扩展组件{
render(){
返回(
{/*某些内容*/}

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

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>
    );
  }
}
导出默认类AwesomeProject扩展组件{
建造师(道具){
超级(道具);
this.state={text:}
}
render(){
返回(
this.setState({text})}
占位符=“文本1”
值={this.state.text}
/>
this.setState({text})}
占位符=“文本2”
值={this.state.text}
/>
);
}
}

从0.42开始高度:
和宽度:接受百分比

在样式表中使用
width:80%
,它就能正常工作

  • 屏幕截图

  • 实例


  • 代码

    从“React”导入React;
    从“react native”导入{Text,View,StyleSheet};
    常数宽度_比例='80%';
    常数高度_比例='40%';
    const styles=StyleSheet.create({
    屏幕:{
    弹性:1,
    对齐项目:“居中”,
    为内容辩护:“中心”,
    背景颜色:“#5A9BD4”,
    },
    方框:{
    宽度:宽度与比例,
    高度:高度与比例,
    对齐项目:“居中”,
    为内容辩护:“中心”,
    背景颜色:“#B8D2EC”,
    },
    正文:{
    尺码:18,
    },
    });
    导出默认值()=>(
    宽度{'\n'}的{宽度{u比例}
    高度的{高度_比例}
    );
    

在样式表中,简单地说:

width: '80%';
而不是:

width: 80%;

继续编码……。:)

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

您可以使用
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',
     },
});
import React,{useffect,useState}来自“React”;
从“react native”导入{维度、视图、文本、样式表};
导出默认常量AwesomeProject()=>{
const[screenData,setScreenData]=useState(Dimensions.get('window').width);
useffect(()=>{
const onChange=()=>{
设置屏幕数据(尺寸.get('window')。宽度);
};
尺寸。添加的列表器(“变更”,一旦变更);
return()=>{Dimensions.removeEventListener('change',onChange);};
});
报税表(
我很高兴
);
}
const styles=StyleSheet.create({
容器:{
弹性:1,
对齐项目:“居中”,
为内容辩护:“中心”,
背景颜色:“#eee”,
},
});

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

width: '80%'

只需在代码中围绕大小添加引号。使用此选项,您可以使用宽度、高度的百分比

input: {
    width: '80%'
}

react native
使用
flex
表示元素的大小和位置。我不确定,但可能是
flex-basis
是您需要的:检查并根据
flex:0.8
之类的内容进行操作。React-Native文档应该在头版提到维度包-这不会让我吃惊…非常有价值的答案。维度实际上非常有用。注意:“尽管尺寸立即可用,但它们可能会更改(例如,由于设备旋转),因此依赖于这些常量的任何渲染逻辑或样式都应尝试在每次渲染时调用此函数,而不是缓存值(例如,使用内联样式,而不是在样式表中设置值)。”请注意,如果您支持横向,并且不手动处理这些布局更改,则使用尺寸标注会在屏幕旋转后中断布局。您可以想象间隔符将包含不同的内容吗?为什么?我能想到
input: {
    width: '80%'
}