我剛剛開始使用React Native並習慣了JSX語法。那是我在說什麼?或者我在談論TypeScript?或者... ES6?反正...在JSX中使用花括號聲明Const
我已經看到了這一點:
const { foo } = this.props;
裏面一類的功能。花括號的用途是什麼?使用它們和不使用它們有什麼區別?
我剛剛開始使用React Native並習慣了JSX語法。那是我在說什麼?或者我在談論TypeScript?或者... ES6?反正...在JSX中使用花括號聲明Const
我已經看到了這一點:
const { foo } = this.props;
裏面一類的功能。花括號的用途是什麼?使用它們和不使用它們有什麼區別?
的解構賦值語法是JavaScript表達式 使得能夠從 對象解包從數組值或屬性,爲不同的變量。
例(ES6):
var person = {firstname: 'john', lastname: 'doe'};
const firstname = person.firstname;
const lastname = person.lastname;
// same as this
const { firstname, lastname } = person;
您可以在MDN
編輯找到更多的信息:也熟悉Python語言的開發者也可以是有趣的與Python語法拆包進行比較。 Python2.7:
>>> _tuple = (1, 2, 3)
>>> a, b, c = _tuple
>>> print(a, b, c)
(1, 2, 3)
隨着Python3的新功能,如PEP 3132你也可以做如下:
>>> _range = range(5)
>>> a, *b, c = _range
>>> print(a, b, c)
0 [1, 2, 3] 4
例子補充說,因爲知道從其他語言就可以掌握JS想法已經類似的方法更快。
看起來它可能是我的權利,但我想通過「應用程序」你的意思是「人」?我猜「first_name」和「last_name」不應該有下劃線。但我明白你的意思! – Varrick
@Varrick,是的,錯別字。下劃線是否有關於相同變量名稱的錯誤。更新的例子。 – wolendranh
Yes this is destructuring assignment feature of ECMASCRIPT 6
For Example :
const { createElement } = React
const { render } = ReactDOM
const title = createElement('h1',{id: 'title', className: 'header'},'Hello
World')
render(title,document.getElementById('react-container'))
here React = { cloneElement : function(){},createElement : function()
{},createFactory : function(),......}
其稱爲[解構(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – Gintoki