gpt4 book ai didi

javascript - React Native 查找文本是否溢出容器

转载 作者:行者123 更新时间:2023-12-04 11:48:05 25 4
gpt4 key购买 nike

我有一个问题,在 react-native 中,我想知道是否有可能知道文本是否溢出容器,想象下面的代码(容器可以是任何东西,View、ScrollView 等无所谓)

<Container>
<Text> Long text...</Text>
</Container>
{textOverflows && <GradientComponent/>}

基本上,如果文本溢出,我会尝试使用 bool 值,并在需要时有条件地在容器底部添加渐变。

最佳答案

使用评论中@Rajesh 的建议,我们可以使用虚拟Text用于测量文本长度的组件。这是一个简单的例子(link to Expo Snack),输入 TextInput导致在当前布局中显示文本的宽度(不是字符数)。文本容器的宽度可以通过 onLayout 类似地获得。或基于 flex 计算。那么我们只需要比较文本宽度和容器宽度就可以判断是否溢出了。

import * as React from 'react';
import {View, Text, TextInput} from 'react-native';

const MyComponent = props => {
const [text, setText] = React.useState('');
const [textWidth, setTextWidth] = React.useState(0);

return (
<View style={{top: 200}}>
<TextInput
style={{borderWidth: 1, borderColor: 'black', height: 30}}
onChangeText={text => setText(text)}
placeholder="Type something"
/>
{/* dummy text to acquire text width. Hide it according to the current layout*/}
<View
style={{height: 0, alignSelf: 'flex-start'}}
onLayout={e => {
setTextWidth(e.nativeEvent.layout.width);
}}>
<Text style={{color: 'white'}}>{text}</Text>
</View>
<View>
<Text>{`Text width: ${textWidth}`}</Text>
</View>
</View>
);
};

export default MyComponent
注意:设置虚拟文本容器样式 alignSelf是至关重要的一步,因为它强制虚拟文本容器紧紧地包裹文本。否则,虚拟文本容器宽度将始终是屏幕的最大宽度。见 this answer更多细节。

关于javascript - React Native 查找文本是否溢出容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59268778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com