How can I measure text in React Native using the Expo framework(如何使用 Expo 框架在 React Native 中测量文本)
问题描述
我目前正在尝试基于 Expo 制作我的 React Native 应用程序,而不会降低到原生依赖项.我想知道是否有一种方法可以测量文本(精确到像素),这样我就可以对布局做出一些明智的选择,而不会以省略或奇怪的换行结束.
I'm currently trying to make my React Native application based on Expo without dropping down to native dependencies. I'm wondering if there is a way to measure text (down to the pixel) so I can make some intelligent choices about layouts without ending up with elides or weird wrapping.
基本上我希望能够做类似的事情:
Basically I'd like to be able to do something like:
//Pseudo Code
class SomeScreen extends React.Component {
//returns a height that fits the width without wrapping
fitToWidth(text, width) {
//I don't have a framework for this in Expo
}
render() {
<View>
<MyText fontSize={fitToWidth('SomeString', 375)} value='Some String' />
</View>
}
}
由于易于测试,如果能在 Expo 中运行它会非常好,我希望有人知道如何实现这一点.我可以下载一些库,但它需要退出 Expo 构建过程,这意味着它不再是可移植的.
It would be really nice to have this run in Expo due to the ease of testing and I'm hoping someone has an idea of how to achieve this. There are some libraries that I can drop down into, but it requires ejecting out of the Expo build process which means it is no longer portable.
我意识到要渲染它还有很多工作要做,但我已经可以计算出视图的宽度和高度,我希望我能找到一种方法来测量文本以根据屏幕大小而不是试图依赖于点.
I realize there's a lot more to do to be able to render this, but I can already figure out the width and height of views and I'm hoping I can find a way to measure text to select a font based on the screen size rather than trying to depend on points.
推荐答案
您需要将 onLayout 事件附加到您的视图.一旦 RN 计算出来,你就会得到尺寸.
You need to attach the onLayout event to your view. Once RN calculates that, you get the dimensions back.
https://facebook.github.io/react-native/docs/view.html#onlayout
这篇关于如何使用 Expo 框架在 React Native 中测量文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Expo 框架在 React Native 中测量文本


基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01