Make view 80% width of parent in React Native

后端 未结 10 2074
孤城傲影
孤城傲影 2020-12-12 16:49

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 straightfor

相关标签:
10条回答
  • 2020-12-12 17:30

    The easiest way to achieve is by applying width to view.

    width: '80%'
    
    0 讨论(0)
  • 2020-12-12 17:33

    You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:

    import EStyleSheet from 'react-native-extended-stylesheet';
    
    const styles = EStyleSheet.create({
      column: {
        width: '80%',
        height: '50%',
        marginLeft: '10%'
      }
    });
    
    0 讨论(0)
  • 2020-12-12 17:39

    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.

    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.

    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.

    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.

    0 讨论(0)
  • 2020-12-12 17:40

    In your StyleSheet, simply put:

    width: '80%';
    

    instead of:

    width: 80%;
    

    Keep Coding........ :)

    0 讨论(0)
提交回复
热议问题