解構賦值
>var {
StyleSheet,
Text,
View
} = React;
這句代碼是ES6 中新增的解構(Destructuring)賦值語句。准許你獲取對象的多個屬性並且使用一條語句將它們賦給多個變量。
上面的代碼等價於:
var StyleSheet = React.StyleSheet; var Text = React.Text; var View = React.View
再看幾個例子,以前,爲變量賦值,只能直接指定值:
var a = 1; var b = 2; var c = 3;
而ES6 允許這樣寫:
var [a, b, c] = [1, 2, 3];
更詳細的內容可參看: 變量的解構賦值
箭頭函數
React Native 裏面經常會出現類似的代碼:
ES6中新增的箭頭操作符 =>
簡化了函數的書寫。操作符左邊爲輸入的參數,而右邊則是進行的操作以及返回的值 Inputs=>outputs
舉幾個栗子感受下:
var array = [1, 2, 3];
//傳統寫法
array.forEach(function(v, i, a) {
console.log(v);
});
//ES6
array.forEach(v = > console.log(v));
var sum = (num1, num2) => { return num1 + num2; }
//等同於:
var sum = function(num1, num2) {
return num1 + num2;
};
更多詳細內容請自行Google,或查看: https://www.imququ.com/post/arrow-function-in-es6.html
延展操作符(Spread operator)
這個 … 操作符(也被叫做延展操作符 - spread operator)已經被 ES6 數組 支持。它允許傳遞數組或者類數組直接做爲函數的參數而不用通過apply。
var people=['Wayou','John','Sherlock'];
//sayHello函數本來接收三個單獨的參數人妖,人二和人三
function sayHello(people1,people2,people3){
console.log(`Hello ${people1},${people2},${people3}`);
}
//但是我們將一個數組以拓展參數的形式傳遞,它能很好地映射到每個單獨的參數
sayHello(...people);//輸出:Hello Wayou,John,Sherlock
//而在以前,如果需要傳遞數組當參數,我們需要使用函數的apply方法
sayHello.apply(null,people);//輸出:Hello Wayou,John,Sherlock
而在 React
中,延展操作符一般用於屬性的批量賦值上。在JSX中,可以使用…運算符,表示將一個對象的鍵值對與ReactElement的props屬性合併。
var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;
//等價於
var props = {};
props.foo = x;
props.bar = y;
var component = <Component foo={x} bar={y} />;
它也可以和普通的XML屬性混合使用,需要同名屬性,後者將覆蓋前者:
var props = { foo: 'default' };
var component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'
更多詳細信息: https://facebook.github.io/react/docs/jsx-spread.html
class
ES6中添加了對類的支持,引入了class關鍵字(其實class在JavaScript中一直是保留字,目的就是考慮到可能在以後的新版本中會用到,現在終於派上用場了)。JS本身就是面向對象的,ES6中提供的類實際上只是JS原型模式的包裝。現在提供原生的class支持後,對象的創建,繼承更加直觀了,並且父類方法的調用,實例化,靜態方法和構造函數等概念都更加形象化。
class PropertyView extends Component {
render() {
return (
<View></View>
)
}
}
//等價於
var PropertyView = React.createClass({
render() {
return (
<View></View>
)
}
})
方法定義(method definition)
ECMAScript 6中,引入了一種名叫方法定義(method definition)的新語法糖,相對於以前的完整寫法,這種簡寫形式可以讓你少寫一個function鍵字.
React.createClass({
render() {
return (
<View></View>
)
}
})
//等價於
React.createClass({
render : function() {
return (
<View></View>
)
}
})