【问题标题】:Using String objects in react-native在 react-native 中使用 String 对象
【发布时间】:2019-07-29 06:44:29
【问题描述】:

我正在努力将我的所有核心业务逻辑转移到模型层,该模型层将用于我的所有项目。

我的项目集主要包括一个基于 Reactjs 构建的面向 Web 客户端的应用程序,一些内部工具也是基于 Reactjs 构建的,以及一个基于 react-native 构建的移动应用程序。

在我的模型层中,我创建了自定义数据类型来处理来自后端的 null/empty 场景并添加自定义格式函数。

以下是我构建的字符串模型的代码。

/**
 Author - Harkirat Saluja
 Git - https://bitbucket.org/salujaharkirat/
 **/

"use strict";

class CustomString {
  static init (value = "") {
    if (value === null) {
      value = "";
    }
    const s = new String(value);

    s.__proto__.upperCaseFormat = function () {
      return this.toUpperCase();
    };
    return s;
  }
}

export default WealthyString;

我调用它的方式如下:-

const firstName = WealthyString.init(firstName);
const lastName = WealthyString.init(lastName);

现在,如果我们看到它返回一个字符串 object

在我的 web 项目中,我在 react 组件中使用如下,效果很好。

<span>{firstName}{" "} {lastName}</span>

但是,在我的 react-native 项目中,如果我以同样的方式使用它,它会抛出 this 错误。 此外,此错误仅在远程调试(如果关闭)时出现,而不是在我连接到 chrome 调试器时出现。

<Text>{firstName}{" "} {lastName}</Text>

所以,为了暂时解决这个问题,我使用了toString() 上面显示的方式附加字符串。但我想知道图书馆有什么问题还是我错过了什么?

更新

所以看起来 String 对象根本无法在 react-native 中使用 Text。因此,要解决此问题,我会执行以下操作:-

const SecondaryText = ({style, children})  => {
      const styleCopy = addLineHeightToStyle(style, 14);
      let dupChildren = children;
      if (dupChildren instanceof String) {
        dupChildren = dupChildren.toString();
      }
      return (
        <ReactNative.Text
          allowFontScaling={false}
          style={[styles.secondaryText, styleCopy]}
        >
          {dupChildren}
        </ReactNative.Text>
      );
};
  1. Text 上构建一个包装器,由 react-native 提供并将对象转换为其中的字符串。
  2. 在字符串组合的情况下使用模板文字连接字符串。

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    考虑对复杂的字符串使用模板文字。例如:

    <Text>{`${firstname} ${lastname}`}</Text>
    

    【讨论】:

      【解决方案2】:

      您要按以下方式更改吗?

      <Text>{firstName +"  "+lastName}</Text>
      

      【讨论】:

        【解决方案3】:

        有多种方法可以做到这一点。编写一个函数并返回连接的字符串。

        const test = (firstName ,lastName) => {
            return firstName+lastName
        }
        

        如果你有一个类,你可以在你的渲染函数中这样做。

        <Text>{this.test()}</Text>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-14
          相关资源
          最近更新 更多