快速入门 React指南 参考 Flux Tips

发布于 2015-07-12 09:59:29 | 1372 次阅读 | 评论: 0 | 来源: 网络整理

如果你事先知道组件需要的全部 Props(属性),JSX 很容易地这样写:

  var component = <Component foo={x} bar={y} />;

修改 Props 是不好的,明白吗 #

如果你不知道要设置哪些 Props,那么现在最好不要设置它:

  var component = <Component />;
  component.props.foo = x; // 不好
  component.props.bar = y; // 同样不好

这样是反模式,因为 React 不能帮你检查属性类型(propTypes)。这样即使你的 属性类型有错误也不能得到清晰的错误提示。

Props 应该被当作禁止修改的。修改 props 对象可能会导致预料之外的结果,所以最好不要去修改 props 对象。

延展属性(Spread Attributes) #

现在你可以使用 JSX 的新特性 - 延展属性:

  var props = {};
  props.foo = x;
  props.bar = y;
  var component = <Component {...props} />;

传入对象的属性会被复制到组件内。

它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。

  var props = { foo: 'default' };
  var component = <Component {...props} foo={'override'} />;
  console.log(component.props.foo); // 'override'

这个奇怪的 ... 标记是什么? #

这个 ... 操作符(也被叫做延展操作符 - spread operator)已经被 ES6 数组 支持。相关的还有 ES7 规范草案中的 Object 剩余和延展属性(Rest and Spread Properties)。我们利用了这些还在制定中标准中已经被支持的特性来使 JSX 拥有更优雅的语法。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务