React Native如何实现文本超出容器时自动缩小字号避免溢出
实现方案
优先使用React Native官方内置属性实现,无需额外引入依赖,性能最优,只需要修改少量代码即可满足需求:
修改后的完整代码
import React, { useState } from 'react' import { Text, View, TextInput, StyleSheet } from 'react-native' const Test = () => { const [text, setText] = useState('') return ( <View style={styles.container}> <View style={styles.board}> <Text style={styles.text} adjustsFontSizeToFit={true} numberOfLines={1} minimumFontScale={0.5} > {text} </Text> </View> <View style={styles.input}> <TextInput onChangeText={setText} /> </View> </View> ) } export default Test const styles = StyleSheet.create({ container:{ backgroundColor: 'purple', flex: 1, justifyContent: 'center', alignItems: 'center' }, board:{ height: 50, width: 100, backgroundColor: 'grey', marginBottom: 20, justifyContent: 'center' // 新增属性让文本在容器内垂直居中 }, input:{ height: 50, width: 100, backgroundColor: 'white' }, text:{ fontSize:14 } })
参数说明
adjustsFontSizeToFit:自动调整字号的开关,设置为true后,当文本长度超出容器容纳范围时,系统会自动缩小字号适配容器numberOfLines:文本最大展示行数,示例设置为1代表文本不允许换行,超出就缩小字号;如果允许文本最多折2行展示,把这个值改成2即可minimumFontScale:字号最小缩放比例,示例设为0.5代表字号最小缩小到初始14号的50%也就是7号,避免字号过小影响可读性,你可以根据自己的需求调整数值
如果需要更灵活的自定义逻辑,比如要同时结合容器高度、宽度动态计算字号,可以引入文本测量库手动计算fontSize,普通场景下上述内置属性已经完全满足需求。
内容的提问来源于stack exchange,提问作者SoF
相关产品推荐
相关产品推荐

