React native项目在做‘展开‘和‘收起’功能如何获取某个View盒子上某个类的高度height,并进行改变重新渲染Dom元素,并用此方法帮我做一个展开和收起功能
时间: 2024-03-09 20:50:42 浏览: 24
要获取某个View盒子上某个类的高度height,可以使用React Native中的`measure()`方法来获取。`measure()`方法可以获取View组件在屏幕上的位置、大小等信息。具体实现如下:
```javascript
import React, { useRef } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
const ExpandableText = ({ text, maxLength }) => {
const [isExpanded, setIsExpanded] = useState(false);
const [textHeight, setTextHeight] = useState(0);
const textRef = useRef();
useEffect(() => {
if (!isExpanded) {
textRef.current.measure((x, y, width, height) => {
setTextHeight(height);
});
}
}, [isExpanded]);
const toggleExpand = () => {
setIsExpanded(prev => !prev);
};
return (
<View style={styles.container}>
<Text
ref={textRef}
numberOfLines={isExpanded ? undefined : maxLength}
onTextLayout={() => {}}
>
{text}
</Text>
{!isExpanded && textHeight > 0 && textHeight > maxLength * 20 && (
<TouchableOpacity onPress={toggleExpand}>
<Text style={styles.expand}>展开</Text>
</TouchableOpacity>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
marginVertical: 10,
},
expand: {
color: '#1890ff',
},
});
export default ExpandableText;
```
在上述代码中,我们使用`useRef()`来获取Text组件的引用,然后在`useEffect()`中使用`measure()`方法获取Text组件的高度。根据Text组件的高度和最大行数,判断是否需要展示“展开”按钮。点击“展开”按钮时,通过修改`isExpanded`状态来切换展开和收起状态。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)