React Native에서 보기 크기 가져오기
특정 뷰의 크기(폭과 높이)를 얻을 수 있습니까?예를 들어 진행 상황을 보여주는 보기가 있습니다.
<View ref='progressBar' style={{backgroundColor:'red',flex:this.state.progress}} />
다른 뷰를 올바르게 정렬하려면 뷰의 실제 너비를 알아야 합니다.이게 가능합니까?
React Native 0.4.2에서는 View 컴포넌트에 프로펠러가 있습니다.이벤트 개체를 가져오는 함수를 전달합니다.이벤트의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);
사이즈는 쉽게 구할 수 있습니다.View타고onLayout 소품
import React from 'react'
import { View } from 'react-native'
export default function index() {
const onLayout=(event)=> {
const {x, y, height, width} = event.nativeEvent.layout;
}
return (
<View onLayout={onLayout}>
<OtherComponent />
</View>
)
}
그onLayout핸들러도 뷰의 크기가 조정될 때마다 호출됩니다.
주요 경고는 다음과 같습니다.onLayout핸들러는 컴포넌트가 마운트된 후 한 프레임 후에 먼저 호출되므로 레이아웃을 계산할 때까지 UI를 숨길 수 있습니다.
기본적으로 크기를 설정하고 변경하려면 레이아웃에서 다음과 같이 설정합니다.
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]}기타 등등.
다음과 같이 사용할 수 있습니다.
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);
}
이 간단한 컴포넌트를 만듭니다.
import React, {Dispatch, SetStateAction} from 'react';
import {View, ViewProps} from 'react-native';
interface GetDimensionsProps {
children: React.ReactNode | React.ReactNode[];
onDimensions: Dispatch<SetStateAction<{height: number; width: number}>>;
viewProps?: ViewProps;
}
export const GetDimensions: React.FC<GetDimensionsProps> = ({
children,
onDimensions,
...viewProps
}: GetDimensionsProps) => {
return (
<View
onLayout={event =>
onDimensions({
width: Math.round(event.nativeEvent.layout.width),
height: Math.round(event.nativeEvent.layout.height),
})
}
{...viewProps}>
{children}
</View>
);
};
// ────────────────────────────────────────────────────────────────────────────────
// usage
// const [dimensions, setDimensions] = useState<{
// height: number;
// width: number;
// }>({width: 0, height: 0});
//
// <GetDimensions onDimensions={setDimensions}>
// {children}
// </GetDimensions>
%를 사용하도록 Dimensions를 설정하는 것이 효과가 있었습니다.width:'100%'
다음은 디바이스 전체 뷰의 치수를 얻기 위한 코드입니다.
var windowSize = Dimensions.get("window");
다음과 같이 사용합니다.
width=windowSize.width,heigth=windowSize.width/0.565
모듈을 직접 사용하여 뷰 크기를 계산할 수 있습니다.정말로.Dimensions주요 창 크기를 알려드립니다.
import { Dimensions } from 'Dimensions';
Dimensions.get('window').height;
Dimensions.get('window').width;
도움이 되길 바랍니다!
업데이트: 현재 뷰에 Flex 어레인지 기능을 탑재한 네이티브를 사용하면 뷰 크기를 계산하는 대신 다양한 케이스에서 우아한 레이아웃 솔루션을 사용하여 깨끗한 코드를 작성할 수 있습니다.
메인 윈도 크기 조정 이벤트에 대응하는 커스텀 그리드 컴포넌트를 구축하면 심플한 위젯 컴포넌트에서 뛰어난 솔루션을 생성할 수 있습니다.
언급URL : https://stackoverflow.com/questions/30203154/get-size-of-a-view-in-react-native
'programing' 카테고리의 다른 글
| 항목이 변경될 때 관찰 가능한 수집 알림 (0) | 2023.04.14 |
|---|---|
| Unix 타임스탬프를 날짜 문자열로 변환 (0) | 2023.04.14 |
| Bash에서 문자열의 첫 번째 문자 제거 (0) | 2023.04.14 |
| c#(WinForms-App) Excel로 데이터 세트 내보내기 (0) | 2023.04.14 |
| ToolTip에 유효성 검사 오류를 표시하는 WPF Style이 텍스트 상자에서는 작동하지만 ComboBox에서는 실패하는 이유는 무엇입니까? (0) | 2023.04.14 |