File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ id : jsx-spread-zh-CN
3
+ title : JSX 展开属性 (Spread Attributes)
4
+ permalink : jsx-spread-zh-CN.html
5
+ prev : jsx-in-depth-zh-CN.html
6
+ next : jsx-gotchas-zh-CN.html
7
+ ---
8
+
9
+ 如果你事先知道模块需要的全部 Props(属性),JSX 很容易地这样写:
10
+
11
+ ``` javascript
12
+ var component = < Component foo= {x} bar= {y} / > ;
13
+ ```
14
+
15
+ ## 修改 Props 是不好的,明白吗
16
+
17
+ 如果你不知道要设置哪些 Props,那么现在最好不要设置它:
18
+
19
+ ``` javascript
20
+ var component = < Component / > ;
21
+ component .props .foo = x; // 不好
22
+ component .props .bar = y; // 同样不好
23
+ ```
24
+
25
+ 这样是反模式,因为 React 不能帮你检查属性类型(propTypes)。这样即使你的 属性类型有错误也不能得到清晰的错误提示。
26
+
27
+ Props 应该被当作禁止修改的。修改 props 对象可能会导致预料之外的结果,所以最好不要去修改 props 对象。
28
+
29
+ ## 扩展属性 (Spread Attributes)
30
+
31
+ 现在你可以使用 JSX 的新特性 - 扩展属性:
32
+
33
+ ``` javascript
34
+ var props = {};
35
+ props .foo = x;
36
+ props .bar = y;
37
+ var component = < Component {... props} / > ;
38
+ ```
39
+
40
+ 传入对象的属性会被复制到模块内。
41
+
42
+ 它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。
43
+
44
+ ``` javascript
45
+ var props = { foo: ' default' };
46
+ var component = < Component {... props} foo= {' override' } / > ;
47
+ console .log (component .props .foo ); // 'override'
48
+ ```
49
+
50
+ ## 这个奇怪的 ` ... ` 标记是什么?
51
+
52
+ 这个 ` ... ` 操作符(也被叫做)已经被 [ ES6 数组] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator ) 支持。相关的还有 ES7 规范草案中的 [ Object 剩余和展开属性(Rest and Spread Properties)] ( https://github.com/sebmarkbage/ecmascript-rest-spread ) 。我们利用了这些还在制定中标准中已经被支持的特性来使 JSX 拥有更优雅的语法。
You can’t perform that action at this time.
0 commit comments