[关闭]
@brizer 2016-01-30T13:17:26.000000Z 字数 1471 阅读 1951

React之props传递


前言

前面讲到了组件的复用方式,本文主要学习props的传递方式。


传递方式

React对组件做了一层抽象,组件对外公布一个简单的props来实现功能,但是内部细节却非常复杂。

手动传递

显示地向下传递props可以确保只公开认为是安全的内部API的子集。

  1. var FancyCheckbox = React.createClass({
  2. render: function() {
  3. var fancyClass = this.props.checked ? 'FancyChecked' : 'FancyUnchecked';
  4. return (
  5. <div className={fancyClass} onClick={this.props.onClick}>
  6. {this.props.children}
  7. </div>
  8. );
  9. }
  10. });
  11. React.render(
  12. <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
  13. Hello world!
  14. </FancyCheckbox>,
  15. document.body
  16. );

...

如果有很多属性呢?还能够一个个地传递吗?
前面说到过,可以通过JSX的...语法来传递props:

  1. return <Component {...this.props} more="values" />;

如果不使用JSX的话,可以通过ES6的Object.assign方法来实现:

  1. return Component(Object.assign({}, this.props, { more: 'values' }));

但是我们把所有属性都传下去既冗余也不安全,可以通过解构剩余参数特性来将未知的属性批量提出来:

  1. var FancyCheckbox = React.createClass({
  2. render: function() {
  3. var { checked, ...other } = this.props;//将checked提出来
  4. var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
  5. // `other` 包含 { onClick: console.log } 但 checked 属性除外
  6. return (
  7. <div {...other} className={fancyClass} />
  8. );
  9. }
  10. });
  11. React.render(
  12. <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
  13. Hello world!
  14. </FancyCheckbox>,
  15. document.body
  16. );

重复利用

如果组件需要使用一个属性又要往下传递,可以直接使用 checked={checked} 再传一次。这样做比传整个 this.props 对象要好,因为更利于重构和语法检查。

  1. var FancyCheckbox = React.createClass({
  2. render: function() {
  3. var { checked, title, ...other } = this.props;
  4. var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
  5. var fancyTitle = checked ? 'X ' + title : 'O ' + title;
  6. return (
  7. <label>
  8. <input {...other}
  9. checked={checked}
  10. className={fancyClass}
  11. type="checkbox"
  12. />
  13. {fancyTitle}
  14. </label>
  15. );
  16. }
  17. });
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注