Program Tip

React Native에서 부모 너비의 80 %보기

programtip 2020. 10. 13. 19:07
반응형

React Native에서 부모 너비의 80 %보기


React Native에서 양식을 만들고 TextInput있으며 화면 너비의 80 % 를 만들고 싶습니다 .

HTML과 일반 CSS를 사용하면 간단합니다.

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

React Native는 display속성, 백분율 너비 또는 자동 여백을 지원하지 않습니다 .

그래서 대신 무엇을해야합니까? 거기에 이 문제의 논의 원주민의 이슈 트래커 반응에서,하지만 제안 된 솔루션은 불쾌한 해킹처럼 보인다.


귀하의 요구에 맞아야합니다.

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>
        );
    }
});

React Native 0.42 height:부터 width:백분율을 허용합니다.

반응 네이티브 비율 높이 / 너비 예제

  • 부모의 비율로 라이브 예제
    자식 너비 / 높이

  • 암호

    import React, { Component } from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    
    const width = '80%';
    const height = '40%';
    
    export default class App extends Component {
      render() {
        return (
          <View style={styles.screen}>
            <View style={styles.box}>
              <Text style={styles.text}>
                {width} of width{'\n'}
                {height} of height
              </Text>
            </View>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      screen: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#7AC36A',
      },
      box: {
        width,
        height,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#F3D1B0',
      },
      text: {
        fontSize: 18,
      },
    });
    

화면 너비에 상대적인 입력을 만들려는 경우 쉬운 방법은 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 }} />

여기서 작업하는 프로젝트를 설정했습니다 . 코드도 아래에 있습니다.

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-extended-stylesheet사용해 볼 수도 있습니다 .

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

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

StyleSheet에 다음을 입력하십시오.

width: '80%';

대신에:

width: 80%;

코딩 유지 ........ :)


부모의 너비를 백분율로 지정하는 데 사용하는 기술은 일부 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
    }
});

기본적으로 flex 속성은 flex 컨테이너에있는 모든 항목의 "전체"flex에 대한 상대적인 너비입니다. 따라서 모든 항목의 합계가 100이면 백분율이 있습니다. 이 예에서는 동일한 결과에 대해 플렉스 값 6 및 4를 사용할 수 있으므로 훨씬 더 유연합니다.

백분율 너비보기를 중앙에 배치하려면 너비가 절반 인 스페이서 두 개를 추가합니다. 따라서 예제에서는 2-6-2가됩니다.

물론 추가 뷰를 추가하는 것은 세상에서 가장 좋은 것은 아니지만 실제 앱에서는 스페이서에 다른 콘텐츠가 포함될 것입니다.


이것이 내가 해결책을 얻은 방법입니다. 간단하고 달콤합니다. 화면 밀도와 무관 :

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>
    );
  }
}

참고 URL : https://stackoverflow.com/questions/33939974/make-view-80-width-of-parent-in-react-native

반응형