TextView.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * 自定义Text组件
  3. * @邠心vbe on 2023/08/30
  4. */
  5. import React from 'react';
  6. import { Text, View } from 'react-native';
  7. const getRadius = (style, fixedAlign) => {
  8. let s = undefined;
  9. if (Array.isArray(style)) {
  10. let res = {}
  11. for (let s of style) {
  12. res = {...res, ...s};
  13. }
  14. s = res;
  15. } else {
  16. s = style
  17. }
  18. var view = {}, text = {}
  19. for (let name in s) {
  20. if (name.indexOf('margin') >= 0) {
  21. view[name] = s[name];
  22. continue;
  23. }
  24. if (name.indexOf('padding') >= 0) {
  25. view[name] = s[name];
  26. continue;
  27. }
  28. if (name.indexOf('color') == 0) {
  29. text[name] = s[name];
  30. continue;
  31. }
  32. if (name.indexOf('font') >= 0) {
  33. text[name] = s[name];
  34. continue;
  35. }
  36. if (name.indexOf('border') >= 0) {
  37. view[name] = s[name];
  38. continue;
  39. }
  40. if (name.indexOf('background') >= 0) {
  41. view[name] = s[name];
  42. continue;
  43. }
  44. if (name.indexOf('text') >= 0) {
  45. text[name] = s[name];
  46. continue;
  47. }
  48. if (name.indexOf('position') >= 0) {
  49. view[name] = s[name];
  50. continue;
  51. }
  52. if (name.indexOf('line') >= 0) {
  53. text[name] = s[name];
  54. continue;
  55. }
  56. view[name] = s[name];
  57. }
  58. if (fixedAlign) {
  59. //修复RN0.7x+渲染中文无法对齐
  60. if (view.alignItems == undefined && view.flexDirection == undefined && text.textAlign == undefined) {
  61. view.alignItems = "center";
  62. view.flexDirection = "row";
  63. }
  64. if (!text.lineHeight) {
  65. if (text.fontSize) {
  66. text.lineHeight = text.fontSize * 1.3;
  67. } else {
  68. text.fontSize = 14;
  69. text.lineHeight = 18.2;
  70. }
  71. }
  72. text.includeFontPadding = false;
  73. }
  74. return {
  75. view: view,
  76. text: text
  77. }
  78. }
  79. const TextView = ({style, ellipsizeMode, numberOfLines, allowFontScaling=false, onPress, onLongPress, fixedAlign=true, children}) => {
  80. const styles = getRadius(style, fixedAlign);
  81. return (
  82. <View style={styles.view}>
  83. <Text
  84. style={styles.text}
  85. allowFontScaling={allowFontScaling}
  86. ellipsizeMode={ellipsizeMode}
  87. numberOfLines={numberOfLines}
  88. onPress={onPress}
  89. onLongPress={onLongPress}>{children}</Text>
  90. </View>
  91. );
  92. };
  93. export default TextView;