乐闻世界logo
搜索文章和话题

How to get React-Native Element's Height From Ref

1个答案

1

In React Native, using ref allows obtaining the instance of a component or element and accessing its properties, including dimension information such as height. Below are specific steps and examples demonstrating how to obtain the height of an element:

Steps:

  1. Create a Ref: Use React.createRef() to create a ref.
  2. Associate the Ref with the Element: Assign the created ref as the ref attribute value of a component.
  3. Measure the Element: Use the onLayout event or the measure method to obtain the element's height.

Using the onLayout Event:

jsx
import React, { Component } from 'react'; import { View, Text } from 'react-native'; class App extends Component { constructor(props) { super(props); this.state = { height: 0 }; } render() { return ( <View onLayout={(event) => { const { height } = event.nativeEvent.layout; this.setState({ height }); }} style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} > <Text>Element height is: {this.state.height} px</Text> </View> ); } } export default App;

Using the measure Method:

jsx
import React, { Component } from 'react'; import { View, Text, TouchableOpacity } from 'react-native'; class App extends Component { constructor(props) { super(props); this.myRef = React.createRef(); } measureHeight = () => { this.myRef.current.measure((x, y, width, height) => { console.log(height); }); } render() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <View ref={this.myRef} style={{ backgroundColor: 'red', width: 100, height: 100 }}> <Text>Test element</Text> </View> <TouchableOpacity onPress={this.measureHeight}> <Text>Measure height</Text> </TouchableOpacity> </View> ); } } export default App;

Explanation:

In the first example, the height is obtained directly from the layout event callback using the onLayout event. This event is triggered when the layout changes and is highly useful for responsive design.

In the second example, the ref and measure method are used. This approach can be invoked at any time to retrieve the element's dimensions and position, offering greater flexibility for scenarios requiring measurements after specific interactions, such as user actions.

Notes:

  • When using the measure method, ensure the element has been rendered on the screen; otherwise, accurate measurement may not be possible.
  • The dimension information provided by onLayout is automatically updated when the layout changes, whereas the measure method can be manually called at any time to obtain the latest dimension information.
2024年6月29日 12:07 回复

你的答案