请解释在这种情况下使用扩展运算符

时间:2016-05-31 11:00:05

标签: javascript reactjs jsx ecmascript-next

我刚开始使用reactjs,我在处理反应数据集时遇到了这个片段:

class MyTextCell extends React.Component {
  render() {
    const {rowIndex, field, data, ...props} = this.props;
    return (
      <Cell {...props}>
        {data[rowIndex][field]}
      </Cell>
    );
  }
}

我的问题如下:

  1. const {rowIndex, field, data, ...props} = this.props;
  2. 据我了解,这可以解释为

    rowIndex= this.props.rowIndex
     field= this.props.field
    

    和...道具将确保它获取this.props的所有对象EXCLUDING rowIndex,field和data。我是对的吗?

    所以我的问题是,如果不是...props说,...somethingElse会被用来制作两个道具,那就不会更好。&#39;看起来不一样。

    1. <Cell {...props}>中道具实际包含什么? this.props的所有对象或者剩下的&#39;除了rowIndex,field,data等之外的其他内容?
    2. 这是摘录片段的链接: https://facebook.github.io/fixed-data-table/getting-started.html

1 个答案:

答案 0 :(得分:3)

<强> 1。 const {rowIndex, field, data, ...props} = this.props;

这是ES6 / 2015功能的实现和建议的功能:

为了清楚地解释它,this.props对象被“解构”为4个新属性,即rowIndexfielddata和{{1} }。 props参数是“object rest”的结果,它收集所有其他属性并将它们放入一个新对象。

因此,您对1号的假设是正确的。 props确实包含...propsrowIndexfield以外的所有道具。关于这一点的好处是你不需要知道或列出任何“其他”属性,它们将自动绑定到新创建的data对象中。

这完全取决于你如何命名,但我同意“重用”名称道具可能有点令人困惑。根据具体情况来看。我倾向于以不同的方式命名。

<强> 2。 props

这是“JSX传播属性”语法(https://facebook.github.io/react/docs/jsx-spread.html)的实现。

这将获取对象中的所有属性,然后将它们分布在目标JSX节点上。

因此,例如,如果您有传入的道具对象:

<Cell {...props}>

这将导致:

{ rowIndex: 1, field: 'foo', data: 'bar', message: 'hello', name: 'Bob' }

当您创建包含组件的高阶组件时,这种事情非常有用,但您不希望将更高阶组件特定的道具传递到包装组件中。

相关问题