2016-11-22 64 views
3

我工作的一個項目,我必須附上一些實用功能爲Javascript Object對象如下:增廣對象的陣營

function isEmpty(a, b) {...} 
Object.prototype.isEmpty = isEmpty; 

現在我面臨的問題是,因爲我與反應工作,我猜測上面的代碼也將isEmpty函數附加到構造的組件上。只要我不使用本地html標籤,即div,span在我的組件內部,這是行得通的,這是不可能的。我收到以下警告

Warning: Unknown prop `isEmpty` on <div> tag. 
Remove these props from the element. For details, see 
https://facebook.github.io/react/warnings/unknown-prop.html 

當我使用本機html標記。有沒有什麼方法可以增加Object對象而不會導致這個錯誤?

+0

你是如何實現組件?你能分享你的HTML或加載相關組件的組件嗎? –

+0

即使我在ReactDOM呈現器中渲染一個簡單的div(

Hello world
),它也會發生 –

+0

您能分享代碼嗎? –

回答

1

問題是,像這樣的對象擴展是可枚舉的。您需要使用defineProperty

順便說一句:這仍然是一個壞主意

+0

不是唯一的問題。它可能會與其他增強或新標準衝突 –

+1

我完全同意,增加'對象'不是一個好主意。但那些屬性是可枚舉的是React問題的根源。 – bonoparte

+0

好點,問題是關於React畢竟,我的評論只是提醒爲什麼這是一個糟糕的主意。 –

1

當您在寫作中編寫jsx標籤時,它將被轉換爲對象(React元素)。因爲你是連接

function sum(a, b) {...} 
Object.prototype.sum = sum; 

它被附加到目前的每對象

var divElement = React.createElement("div", { id: "test" }); 

現在 -

所以

<div id="test"> 
</div> 

轉化爲以下object

可能是你應該考慮提供一個Util.js它將包含所有的實用方法,並不附加到對象的原型。因爲它會引起不良副作用。

您可以導入Util.js任何地方你需要和使用這些方法。

例如 -

module.exports = { 
    sum(a, b) {...} 
}; 
+0

是的,如果我的方法行不通,我想我必須這樣做,坦率地說,我現在傾向於這種方法,因爲我知道增強是一種不好的做法。謝謝! :) –

0

問題

所有JSX元素首先作爲對象創建(WitVault解釋JSX如何transpiled到可以運行在瀏覽器平原JS)。 React採用React支持的那些對象及其屬性,並將它們映射到DOM元素。如果有React不知道的屬性,它會顯示警告,因爲它可能是「你不知道你在做什麼」或「你犯了一個錯誤」的情況,因此你不會得到你期望的行爲。

由於您編輯了對象的原型,所有對象(也是那些由React創建的對象)都獲得屬性sum,對於基元html元素,React不知道如何映射sum屬性。

正如Juan Mendes指出的那樣,extending native objects is bad practice。如果您在React項目中擴展Object.prototype,則確實無法避免您遇到的問題。

解決方案1:導出/導入UTIL功能

由於陣營自帶browserify可以替代進口的實用方法。這有兩個好處:

  • 你並不需要擴展本地對象
  • 你表達清楚何處使用來自這些方法,是因爲他們有使用它的文件中的import語句。

在ES6

// util/objectSum.js 
export default function objectSum(object) { ... }; 

// anotherFile.js 
import objectSum from 'utils/objectSum.js'; // assuming utils/ is directly under the root path of your project (root path can be configured in webpack.config if you use webpack) 

const object = ?; // the object you want to sum 
const sum = objectSum(object); 

在ES5

// util/objectSum.js 
module.exports = function(object) { ... }; 

// anotherFile.js 
var objectSum = require('utils/objectSum.js'); // assuming utils/ is directly under the root path of your project (root path can be configured in webpack.config if you use webpack) 

const object = ?; // the object you want to sum 
const sum = objectSum(object); 

解決方案2:使用ES6類

在ES6你也可以創建一個類的總和法。下面是一個例子:

class NumberList { 
    constructor(arrayOfNumbers) { 
     this.numbers = arrayOfNumbers; 
     this.sum = this.sum.bind(this); 
    } 

    sum() { 
     return this.numbers.reduce((sum, next) => sum + next, 0); 
    } 
} 

const numberList = new NumberList([1, 2, 3]); 
numberList.sum(); // -> 6