如何使用 Expo 框架在 React Native 中测量文本 [英] How can I measure text in React Native using the Expo framework

查看:24
本文介绍了如何使用 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 中测量文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆