React Native에서 뷰 크기 가져 오기 높이)를 얻을 수 있습니까? 예를 들어

특정보기의 크기 (너비와 높이)를 얻을 수 있습니까? 예를 들어 진행 상황을 보여주는 뷰가 있습니다.

<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} /> 

다른 뷰를 올바르게 정렬하려면 뷰의 실제 너비를 알아야합니다. 이게 가능해?



답변

React Native 0.4.2부터 View 구성 요소에는 onLayoutprop가 있습니다. 이벤트 객체를받는 함수를 전달하십시오. 이벤트 nativeEvent에는보기의 레이아웃이 포함됩니다.

<View onLayout={(event) => {
  var {x, y, width, height} = event.nativeEvent.layout;
}} />

onLayout뷰의 크기가 변경 될 때마다 핸들러는 호출됩니다.

주된주의 사항은 onLayout구성 요소가 마운트 된 후 핸들러가 먼저 한 프레임에서 호출되므로 레이아웃을 계산할 때까지 UI를 숨길 수 있습니다.


답변

이것이 나를 위해 일한 유일한 것입니다.

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

export default class Comp extends Component {

  find_dimesions(layout){
    const {x, y, width, height} = layout;
    console.warn(x);
    console.warn(y);
    console.warn(width);
    console.warn(height);
  }
  render() {
    return (
      <View onLayout={(event) => { this.find_dimesions(event.nativeEvent.layout) }} style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('Comp', () => Comp);


답변

기본적으로 크기를 설정하고 변경하려면 레이아웃에서 다음과 같이 상태로 설정하십시오.

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, View } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'yellow',
  },
  View1: {
    flex: 2,
    margin: 10,
    backgroundColor: 'red',
    elevation: 1,
  },
  View2: {
    position: 'absolute',
    backgroundColor: 'orange',
    zIndex: 3,
    elevation: 3,
  },
  View3: {
    flex: 3,
    backgroundColor: 'green',
    elevation: 2,
  },
  Text: {
    fontSize: 25,
    margin: 20,
    color: 'white',
  },
});

class Example extends Component {

  constructor(props) {
    super(props);

    this.state = {
      view2LayoutProps: {
        left: 0,
        top: 0,
        width: 50,
        height: 50,
      }
    };
  }

  onLayout(event) {
    const {x, y, height, width} = event.nativeEvent.layout;
    const newHeight = this.state.view2LayoutProps.height + 1;
    const newLayout = {
        height: newHeight ,
        width: width,
        left: x,
        top: y,
      };

    this.setState({ view2LayoutProps: newLayout });
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.View1}>
          <Text>{this.state.view2LayoutProps.height}</Text>
        </View>
        <View onLayout={(event) => this.onLayout(event)}
              style={[styles.View2, this.state.view2LayoutProps]} />
        <View style={styles.View3} />
      </View>
    );
  }

}


AppRegistry.registerComponent(Example);

래퍼로 다른보기가있는 다른 구성 요소에서이를 사용하여 수정 방법을 훨씬 더 변형시킬 수 있으며 onResponderRelease 콜백을 만들어 터치 이벤트 위치를 상태로 전달한 다음 자식 구성 요소로 전달할 수 있습니다. 속성으로 설정하면 onLayout 업데이트 상태를 재정의 할 수 있습니다 {[styles.View2, this.state.view2LayoutProps, this.props.touchEventTopLeft]}.


답변

Dimensions모듈을 직접 사용하고 뷰 크기를 계산할 수 있습니다. 실제로, Dimensions기본 창 크기를 제공하십시오.

import { Dimensions } from 'Dimensions';

Dimensions.get('window').height;
Dimensions.get('window').width;

당신을 도울 수 있도록 노력하겠습니다!

업데이트 : 오늘 기본 StyleSheet사용 Flex 하여 뷰를 정렬하면 뷰 크기를 계산하는 대신 넓은 경우 우아한 레이아웃 솔루션으로 깨끗한 코드를 작성할 수 있습니다 …

기본 창 크기 조정 이벤트에 응답 하는 사용자 지정 그리드 구성 요소를 작성 하더라도 간단한 위젯 구성 요소에서 좋은 솔루션을 생성 할 수 있습니다.


답변

아마도 당신은 사용할 수 있습니다 measure:

measureProgressBar() {
    this.refs.welcome.measure(this.logProgressBarLayout);
},

logProgressBarLayout(ox, oy, width, height, px, py) {
  console.log("ox: " + ox);
  console.log("oy: " + oy);
  console.log("width: " + width);
  console.log("height: " + height);
  console.log("px: " + px);
  console.log("py: " + py);
}


답변

나를 위해 크기를 사용하도록 설정하는 비율은 나를 위해 일한 것입니다.
width:'100%'


답변

다음은 장치의 전체 뷰의 크기를 가져 오는 코드입니다.

var windowSize = Dimensions.get("window");

다음과 같이 사용하십시오.

width=windowSize.width,heigth=windowSize.width/0.565