react-native - react-native 自定义文本省略号以在省略号后添加“更多”
解决方案
这是一个快速的解决方法。创建一个将文本作为参数的函数,并使用更多按钮显示截断的文本。单击后,我们将使用较少的按钮呈现全文。
const MoreLessComponent = ({ truncatedText, fullText }) => {
const [more, setMore] = React.useState(false);
return (
<Text>
{!more ? `${truncatedText}...` : fullText}
<TouchableOpacity onPress={() => setMore(!more)}>
<Text>{more ? 'less' : 'more'}</Text>
</TouchableOpacity>
</Text>
);
};
const MoreInfo = (text, linesToTruncate) => {
const [clippedText, setClippedText] = React.useState(false);
return clippedText ? (
<MoreLessComponent truncatedText={clippedText} fullText={text} />
) : (
<Text
numberOfLines={linesToTruncate}
ellipsizeMode={'tail'}
onTextLayout={(event) => {
//get all lines
const { lines } = event.nativeEvent;
//get lines after it truncate
let text = lines
.splice(0, linesToTruncate)
.map((line) => line.text)
.join('');
//substring with some random digit, this might need more work here based on the font size
//
setClippedText(text.substr(0, text.length - 9));
}}>
{text}
</Text>
);
};
现在这样称呼
<View>
{MoreInfo('Change code in the editor and watch it change on your phone! Save to get a shareable url.')}
</View>
这是小吃https://snack.expo.io/@saachitech/react-native-more-less
推荐阅读
- vb.net - 如何使用 vb.net 在子目录结构中查找并打开最新的 txt 文件
- android - Android将PCM字节数组写入wav文件
- docker - 在使用 Paket 从项目构建的 Docker 映像中找不到 Microsoft.AspNetCore.App 2.2.7
- c - 如何将更改保存在 c 上的动态树上?
- javascript - 带有 CSS 变量冒泡的 JavaScript 鼠标位置剪辑路径效果
- docker - 具有撰写文件单节点和本地映像的 docker 服务
- python - 计算列中工资范围的平均值
- sql - 如何计算sql表中3(或更多)行内每对之间差异的总和
- compare - 如何比较两个不等式是否相同
- javascript - 如何使用 JavaScript 创建表单并在不重新加载页面的情况下提交