问题
I have a React Native app with a FlatList.
My logic that I have added was whenever the Character at 100th position is not empty an Expand/Collapse arrow should be added as shown below. NO arrow icon for short messages.
Well, this is bad logic!! Now when I change my app font to Large/small this logic won't work. It doesn't work for Chinese characters too LOL. So it shouldn't be based on number of characters.
{ alert.charAt(100) !== "" ?
arrowClicked === true ?
<Icon type='materialicons' name='arrow-drop-up' onPress={()=>{this.setFullLength()}} />
:
<Icon type='materialicons' name='arrow-drop-down' onPress={()=>{this.setFullLength()}} />
: null
}
It should detect that the text is long and being truncated. How can I implement this?? Please Help!!!!
回答1:
You should use the onTextLayout and decide the line length using something like below.
function CustomText(props) {
const [showMore, setShowMore] = React.useState(false);
const [lines, setLines] = React.useState(props.numberOfLines);
const onTextLayout = (e) => {
setShowMore(
e.nativeEvent.lines.length > props.numberOfLines && lines !== 0
);
};
return (
<View>
<Text numberOfLines={lines} onTextLayout={onTextLayout}>
{props.children}
</Text>
{showMore && (
<Button title="Show More"
onPress={() => {
setLines(0);
setShowMore(false);
}}
/>
)}
{!showMore && (
<Button title="Hide More"
onPress={() => {
setLines(props.numberOfLines);
}}
/>
)}
</View>
);
}
Usage
const text =
'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to mak';
<CustomText numberOfLines={2}>{text}</CustomText>
You can pass other props like styles as well.
来源:https://stackoverflow.com/questions/62316417/truncate-text-react-native