Make view 80% width of parent in React Native

后端 未结 10 2098
孤城傲影
孤城傲影 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: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 (
                
                    
                        {/* Some content */}
                    
    
                    
                
            );
        }
    }
    
    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.

提交回复
热议问题