简体   繁体   English

包括原型 function 全局(反应)

[英]include prototype function globally (react)

I have the following function to quickly replace words in a string (with multiple occurences):我有以下 function 可以快速替换字符串中的单词(多次出现):

String.prototype.replaceAll = function (search, replacement) {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
};

This function works as expected.这个 function 按预期工作。 I need this function in multiple components (files) and functions, so I add this function directly at the beginning of every file.我在多个组件(文件)和功能中需要这个 function,所以我直接在每个文件的开头添加这个 function。 Is there an easy solution to include this kind of functions globally to a project without adding it separately to every file?是否有一种简单的解决方案可以将此类功能全局包含到项目中,而无需将其单独添加到每个文件中?

Edit:编辑:

// strings.js
import React from 'react';
String.prototype.replaceAll = function (search, replacement) {
  var target = this;
  return target.replace(new RegExp(search, 'g'), replacement);
};

Should I export this function or how can I import this function?我应该导出这个 function 还是如何导入这个 function? Can I add import strings.js at the top of App.js?我可以在 App.js 的顶部添加import strings.js吗?

If you modify the string prototype, your work is done.如果你修改了字符串原型,你的工作就完成了。 The function will be available everywhere immediately. function 将立即随处可用。 However, you should be aware that modifying the prototype of types like String is frowned upon: https://flaviocopes.com/javascript-why-not-modify-object-prototype/但是,您应该知道修改 String 等类型的原型是不受欢迎的: https://flaviocopes.com/javascript-why-not-modify-object-prototype/

Also, if you are using TypeScript, you won't see the new function without casting the string to some type of your own.此外,如果您使用 TypeScript,您将不会看到新的 function 而不将字符串转换为您自己的某种类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM