問題
所有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
你是如何實現組件?你能分享你的HTML或加載相關組件的組件嗎? –
即使我在ReactDOM呈現器中渲染一個簡單的div(
您能分享代碼嗎? –