Javascript 在 React Native 中使视图宽度为父级的 80%
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33939974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make view 80% width of parent in React Native
提问by Mark Amery
I'm creating a form in React Native and would like to make my TextInput
s 80% of the screen width.
我正在 React Native 中创建一个表单,并希望使我的TextInput
s 为屏幕宽度的 80%。
With HTML and ordinary CSS, this would be straightforward:
使用 HTML 和普通 CSS,这将很简单:
input {
display: block;
width: 80%;
margin: auto;
}
Except that React Native doesn't support the display
property, percentage widths, or auto margins.
除了 React Native 不支持display
属性、百分比宽度或自动边距。
So what should I do instead? There's some discussion of this problemin React Native's issue tracker, but the proposed solutions seem like nasty hacks.
那我应该怎么做呢?在 React Native 的问题跟踪器中有一些关于这个问题的讨论,但所提出的解决方案看起来像讨厌的黑客。
回答by neciu
That should fit your needs:
这应该符合您的需求:
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>
);
}
});
回答by GollyJer
As of React Native 0.42 height:
and width:
accept percentages.
从 React Native 0.42 开始height:
并width:
接受百分比。
Use width: 80%
in your stylesheets and it just works.
width: 80%
在您的样式表中使用它就可以了。
Screenshot
Live Example
Child Width/Height as Proportion of ParentCode
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> );
截屏
代码
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> );
回答by Nader Dabit
If you are simply looking to make the input relative to the screen width, an easy way would be to use Dimensions:
如果您只是想让输入相对于屏幕宽度,一个简单的方法是使用 Dimensions:
// 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 }} />
I've set up a working project here. Code is also below.
我在这里建立了一个工作项目。代码也在下面。
https://rnplay.org/apps/rqQPCQ
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);
回答by Krishna Raj Salim
In your StyleSheet, simply put:
在您的样式表中,只需输入:
width: '80%';
instead of:
代替:
width: 80%;
Keep Coding........ :)
继续编码........ :)
回答by vitalets
You can also try react-native-extended-stylesheetthat supports percentage for single-orientation apps:
您还可以尝试支持单向应用程序百分比的react-native-extended-stylesheet:
import EStyleSheet from 'react-native-extended-stylesheet';
const styles = EStyleSheet.create({
column: {
width: '80%',
height: '50%',
marginLeft: '10%'
}
});
回答by dsdeur
The technique I use for having percentage width of the parent is adding an extra spacer view in combination with some flexbox. This will not apply to all scenarios but it can be very helpful.
我用于获得父级百分比宽度的技术是添加一个额外的间隔视图和一些 flexbox。这并不适用于所有场景,但它可能非常有帮助。
So here we go:
所以我们开始:
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
}
});
Basically the flex property is the width relative to the "total" flex of all items in the flex container. So if all items sum to 100 you have a percentage. In the example I could have used flex values 6 & 4 for the same result, so it's even more FLEXible.
基本上, flex 属性是相对于 flex 容器中所有项目的“总” flex 的宽度。因此,如果所有项目总和为 100,您就有一个百分比。在示例中,我可以使用 flex 值 6 和 4 来获得相同的结果,因此它更加灵活。
If you want to center the percentage width view: add two spacers with half the width. So in the example it would be 2-6-2.
如果要使百分比宽度视图居中:添加两个宽度为一半的间隔。所以在这个例子中它将是 2-6-2。
Of course adding the extra views is not the nicest thing in the world, but in a real world app I can image the spacer will contain different content.
当然,添加额外的视图并不是世界上最好的事情,但在现实世界的应用程序中,我可以想象间隔器将包含不同的内容。
回答by Shayan Moghadam
I have an updated solution (late 2019) , to get 80% width of parent Responsively with Hooksit work's even if the device rotate.
我有一个更新的解决方案(2019 年末),即使设备旋转,它也可以使用 Hooks 响应地获得父级的 80% 宽度。
You can use Dimensions.get('window').width
to get Device Width in this example you can see how you can do it Responsively
您可以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',
},
});
回答by sagar suri
This is the way I got the solution. Simple and Sweet. Independent of Screen density:
这就是我得到解决方案的方式。简单而甜蜜。与屏幕密度无关:
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>
);
}
}