React Native onTextLayout with overflow hidden



我正在尝试在我的 React Native 应用程序中构建一个动画"查看更多/丢弃"按钮。我计划使用 onLayout 或 onTextLayout 方法来获取文本的高度,然后使用动画和溢出:"隐藏"在单击按钮时显示它。代码如下所示:

<Animated.View style={{overflow: "hidden", height: heightAnim }}>
<Text
onTextLayout={({ nativeEvent: { lines } }) => {
//We set the maxHeight to number of lines * the height of a line
setContentHeight(lines.length * 14);
}}
>
{description}
//Description can range between 0 to 15 lines
</Text>
</Animated.View>
<TouchableWithoutFeedback onPress={() => handleOpen()}>
<Text>
{open ? "Discard" : "See More"}
</Text>
</TouchableWithoutFeedback>

但是,onLayout和onTextLayout只给我屏幕上可见的文本的大小。 举个例子,如果文本持续 14 行,而我最初显示 2 行高度为 14,则 onLayout 将返回高度 28,而 onTextLayout 行将只返回前 2 行。这导致我的动画的 maxHeight 也是 28,因此隐藏的文本保持隐藏状态。

如何访问文本的所有高度/行的高度,包括隐藏部分?

感谢您的帮助!

<View>
<ScrollView style={{height:0}}>
<Text onTextLayout={(e)=>{/* measure the text here */}}>{text}</Text>
</ScrollView>
<Text>{text}</Text>
</View>

您可以渲染文本两次,其中一个文本用高度为 0 的 ScrollView 换行。然后,您可以测量文本的所有高度/行

您可以使用这种简单的方法,它工作正常,但是如果您需要动态检查文本是否超过 1 行,则需要使用onTextLayout并对其进行检查。

const [lines, setLines] = useState(1)

<View>
<Text numberOfLines={lines}>This is some long text here This is some long 
text here This is some long text here This is some long text here This is 
some long text here This is some long text here This is some long text here 
This is some long text here This is some long text here This is some long 
text here This is some long text here This is some long text here 
</Text>
<TouchableOpacity onPress={() => {
lines == 999 ? setLines(1) : setLines(999)
}}>
<Text style={{ color: 'blue' }}>{lines == 999 ? "Less" : "More"}</Text>
</TouchableOpacity>
</View>

更新:

或者您可以做的是将文本包装到TouchableOpacity中,当按下它时,它会像这样展开

const [lines, setLines] = useState(1)

<View>

<TouchableOpacity onPress={() => {
lines == 999 ? setLines(1) : setLines(999)
}}>
<Text numberOfLines={lines}>This is some long text here This is some long 
text here This is some long text here This is some long text here This is 
some long text here This is some long text here This is some long text here 
This is some long text here This is some long text here This is some long 
text here This is some long text here This is some long text here 
</Text>
</TouchableOpacity>
</View>

最新更新