如何在Android的React Native中调整字体大小以适合视图?

如何在Android的React Native中调整字体大小以适合视图?

问题描述:

如何在React Native中使视图内部的文本字体大小自动改变?

How I can make the font size of the text auto change inside a view in react native?

我有不同长度的文本,其中一些不适合视图,因此减小了字体大小.我检查了文档,发现 但是它仅适用于iOS,而我需要适用于Android.

I have text with different lengths, some of which doesn't fit the view so decreased the font size. I have checked the docs and found this but it's for iOS only and I need it for Android.

它可以与按钮和touchableopacity等其他组件一起使用吗?

And does it work with other components like button and touchableopacity?

经过改进的Jeffy Lee代码对我有用

A bit improved Jeffy Lee code worked for me

const AdjustLabel = ({
  fontSize, text, style, numberOfLines
}) => {
  const [currentFont, setCurrentFont] = useState(fontSize);

  return (
    <Text
      numberOfLines={ numberOfLines }
      adjustsFontSizeToFit
      style={ [style, { fontSize: currentFont }] }
      onTextLayout={ (e) => {
        const { lines } = e.nativeEvent;
        if (lines.length > numberOfLines) {
          setCurrentFont(currentFont - 1);
        }
      } }
    >
      { text }
    </Text>
  );
};