Javascript React:在何处扩展对象原型

Javascript React:在何处扩展对象原型,javascript,reactjs,prototype,create-react-app,Javascript,Reactjs,Prototype,Create React App,我使用创建了一个纯React应用程序。我想扩展String类,并在一个或多个组件中使用它。例如: String.prototype.someFunction = function () { //some code } (您可能需要查看以了解有关扩展对象原型的更多信息。) 是的,我可以在组件旁边定义它,并在中使用它。但是,什么是最好和最干净的方式呢 我应该把它写为类方法还是写在组件didmount或其他东西里面 编辑: 在React(或JavaScript)中扩展对象原型是否“可以”?T

我使用创建了一个纯React应用程序。我想扩展
String
类,并在一个或多个组件中使用它。例如:

String.prototype.someFunction = function () {
    //some code
}
(您可能需要查看以了解有关扩展对象原型的更多信息。)

是的,我可以在组件旁边定义它,并在中使用它。但是,什么是最好和最干净的方式呢

我应该把它写为
类方法
还是写在
组件didmount
或其他东西里面

编辑:

在React(或JavaScript)中扩展对象原型是否“可以”?

TLDR回答:没有! --细致入微的回答--

我想做的是扩展纯JavaScript类,比如字符串类,这是JavaScript中非常常见的任务

在React(或JavaScript)中扩展对象原型是否“可以”

在JavaScript中扩展/修改本机原型是一项艰巨的任务,而且,与您所说的相反,大多数专业开发人员并不经常这样做。问题是,因为它打破了封装原则,修改了全局状态。然而,与许多规则一样,可能也有罕见的例外。例如:你正在做一个玩具项目,不需要产品质量,你是唯一一个接触到这个代码库的开发人员,或者你的代码永远不会成为其他人的依赖

如果您有一个非常好的理由,并且确实知道自己在做什么,并且完全了解对运行时环境和依赖项的本机数据类型/行为进行修改的潜在后果,那么您可能会找到一些适用于此实践的有效用例。但很可能不是,或者至少不是经常。几乎从来没有

如果你只是追求方便/语法上的甜头,你最好引入实用函数(从lodash、下划线或ramda之类的函数中),并学习练习函数组合。但是如果您真的致力于面向对象的范例,那么您可能应该只是“子类化”本机数据类型,而不是修改它们

因此,与其像这样修改类的原型,不如:

String.prototype.somethingdupid=函数(){
return[].map.call(此,函数(字母){
if((Math.random()*1)>.5)返回字母.toUpperCase()
else返回信函。toLowerCase()
}).加入(“”)
}
console.log('这是一个愚蠢的字符串'.somethingdupid())
用于TypeScript语言用户 使用expo cli 36在基于javascript的react本机项目上进行了测试,是在使用Angular 7时编写的

我犯了一个错误,把我带到了这里。。。 我使用的是基于js的react native。 以前我写了一个JS库,后来由于一些需要,我把它改成了TS,在切换到Angular之后,我不得不用它创建一个坚定的库,以便在那个环境中工作

不,我复制了这些文件在这里,我有一个错误,我来到这个线程,但所有的错误都消失了,一旦我第一次编译它,它完全工作

下面是我如何使用它的:

我有实用程序类
utility.ts

export class Utility {
  /**
   * Returns False If Incoming Variable Is Not Null, void or Undefined, Otherwise True
   */
  public static isNullOrUndefined(obj: any|void): boolean {
    // return obj == null // juggling-check
    return typeof obj === 'undefined' || obj === null; // strict-check
  }

  /**
   * Returns False If Incoming Variable Does Not Contains Data, Otherwise True
   */
  public static isNullOrUndefinedOrEmpty(obj: any|void): boolean {
    if (Utility.isNullOrUndefined(obj)) {
        return true;
    }

    // typeof for primitive string, instanceof for objective string
    if (typeof(obj) === 'string' || obj instanceof String) {
      return (obj as string).valueOf() === '';
    } else if (obj instanceof Array) {
      return (obj as Array<any>).length === 0;
    }
    throw new Error('Not Supported Exception');
  }
...
}
import { Utility } from './Utility';

/**
 * Support StringComparision Options
 * https://stackoverflow.com/questions/10636871/ordinal-string-compare-in-javascript
 */
String.prototype.indexOfString = function(searchString: string, position?: number, comparision?: StringComparison): number {
  return Utility.indexOfString(this, searchString, position, comparision);
};

String.prototype.insertAt = function(index: number, strText: string): string {
  return this.substr(0, index) + strText + this.substr(index);
};

String.prototype.removeAt = function(index: number, count: number): string {
  if (Utility.isNullOrUndefined(count)) {
    count = this.length - index;
  }
  return this.substr(0, index) + this.substr(index + count);
};
最后我有了扩展名文件
Extensions.ts

export class Utility {
  /**
   * Returns False If Incoming Variable Is Not Null, void or Undefined, Otherwise True
   */
  public static isNullOrUndefined(obj: any|void): boolean {
    // return obj == null // juggling-check
    return typeof obj === 'undefined' || obj === null; // strict-check
  }

  /**
   * Returns False If Incoming Variable Does Not Contains Data, Otherwise True
   */
  public static isNullOrUndefinedOrEmpty(obj: any|void): boolean {
    if (Utility.isNullOrUndefined(obj)) {
        return true;
    }

    // typeof for primitive string, instanceof for objective string
    if (typeof(obj) === 'string' || obj instanceof String) {
      return (obj as string).valueOf() === '';
    } else if (obj instanceof Array) {
      return (obj as Array<any>).length === 0;
    }
    throw new Error('Not Supported Exception');
  }
...
}
import { Utility } from './Utility';

/**
 * Support StringComparision Options
 * https://stackoverflow.com/questions/10636871/ordinal-string-compare-in-javascript
 */
String.prototype.indexOfString = function(searchString: string, position?: number, comparision?: StringComparison): number {
  return Utility.indexOfString(this, searchString, position, comparision);
};

String.prototype.insertAt = function(index: number, strText: string): string {
  return this.substr(0, index) + strText + this.substr(index);
};

String.prototype.removeAt = function(index: number, count: number): string {
  if (Utility.isNullOrUndefined(count)) {
    count = this.length - index;
  }
  return this.substr(0, index) + this.substr(index + count);
};
在这里,我将所有这些文件放在一个名为
util
的文件夹中,这一点都不重要,我可以直接从扩展名访问实用程序,反之亦然(或者直到现在我还没有遇到任何问题)

现在虽然我仍然不能在react组件中使用扩展,但如果我添加一个简单的导入:
import'../util/extensions';

我是这样测试的:

import React from 'react';
import { Text, View } from 'react-native';

import '../util/Extensions'; //my import

const SurveyScreen = props => {
    const z = 'sdwqew';
    const x = z.insertAt(2,'hassan'); //function from my custom extensions
    return (
        <View>
            <Text>Hello World</Text>
            <Text>{x}</Text>
        </View>
    );
}

export default SurveyScreen;
从“React”导入React;
从“react native”导入{Text,View};
导入“../util/Extensions”;//我的导入
const SurveyScreen=道具=>{
常数z='sdwqew';
const x=z.insertAt(2,'hassan');//来自自定义扩展的函数
返回(
你好,世界
{x}
);
}
导出默认调查屏幕;
注意现在我没有足够的时间来全面概述我的旧代码,但问题是

第二注释:如果在实用程序中导入扩展,它会警告我,允许循环,但可能导致未初始化的值。考虑重构以消除循环的需要。


如果我没有看到VSCode上的一些错误,但是它编译得很好,没有警告…

您是否正在尝试扩展该组件?理想情况下,
class someComponent会扩展您想要从{render(){}扩展的组件
通常类似于
class App扩展组件{render(){}
@Aaqib不,先生。我想做的是扩展纯JavaScript类,比如
String
class,这是JavaScript中非常常见的任务。请参阅。我想知道是否有特殊的(或更优雅的)要做到这一点,不仅仅是把它写在一个组件旁边。我是一名专业人士,我一直都这么做。这可能非常方便。我不是在这里提出“没有真正的苏格兰人”的论点。我说这“不是大多数专业开发人员经常做的事情。”因此,你的陈述实际上支持了我所说的。我的目的是阻止这种做法。如果你发现这样的做法很方便,我会发抖地想,他们必须在什么样的代码库中工作才能使这样的事情“方便”我从来没有在任何地方工作过,这些地方不会在公共关系代码审查中立即标记,并且需要更改才能被接受。