我有一个问题,在react-native中,我想知道是否有可能知道文本是否溢出容器,想象一下以下代码(容器可以是任何东西,View、ScrollView等都无关紧要)
<Container>
<Text> Long text...</Text>
</Container>
{textOverflows && <GradientComponent/>}
我正在尝试创建一个布尔值,以检查文本是否溢出,并在需要时在容器底部有条件地添加渐变。
我有一个问题,在react-native中,我想知道是否有可能知道文本是否溢出容器,想象一下以下代码(容器可以是任何东西,View、ScrollView等都无关紧要)
<Container>
<Text> Long text...</Text>
</Container>
{textOverflows && <GradientComponent/>}
我正在尝试创建一个布尔值,以检查文本是否溢出,并在需要时在容器底部有条件地添加渐变。
根据评论中@Rajesh的建议,我们可以使用一个虚拟的Text
组件来测量文本长度。这里有一个简单的例子(链接到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。
text.legth >container.width ? style= {styles.gradientCompoennt} : style={styles.whatever}
text.length
将是文本字符串中字符的数量,并不代表文本的宽度。 - user56reinstatemonica8