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 中测量文本
基础教程推荐
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
