【问题标题】:Is this a type annotation, an object, or something else?这是类型注释、对象还是其他?
【发布时间】:2018-10-22 20:57:42
【问题描述】:

我在查看 this code example 并偶然发现了这种语法:

import React, { Component } from 'react';

const PrivateRoute = ({component:Component, ...rest}) => (
//(...)
  <Component {...props} />
// (...)
);

我对@9​​87654323@ 部分感到困惑。这看起来像一个静态类型注解,有点像一个泛型注解,但这是 Javascript,所以它只能是一个对象,对吧?如果这是一个对象,这是否意味着该函数正在为其自己的参数分配一个默认的空 Component 对象?如果是这样,它如何能够从调用者那里接收它,例如(根据示例):

<PrivateRoute path="/protected" component={Protected} />

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这是来自 ES6 的名为 destructuring 的对象。下面

    const PrivateRoute = ({component:Component, ...rest}) => (
    

    表示任何将作为component 属性传递给PrivateRoute 的内容,都可以使用Component 变量来使用。

    【讨论】:

    • 这肯定会和 Typescript 冲突?
    • @murat 不,打字稿注释在对象之后,{ a: b } : { a: type }。是的,这很令人困惑(这就是为什么我最初把这个误认为是错误的)
    • 在 Typescript 中你会使用 ({component: Component, ...rest}: {component: Component, rest: any})
    • 啊,我明白了。谢谢。这实际上对 ReactJs 非常有用。
    • @Asik 是的,它只是任意名称。但是由于 React 的约定,显然有人想将一个组件传递给 component 属性,因此在名称中使用大写名称:Component
    【解决方案2】:

    我对 :Component 部分感到困惑。这看起来像一个静态类型注释

    是的,它看起来像,因为全局 Component 类的名称被遮蔽了,因此看起来像 component 使用 Typescript 注释作为 Component 键入。但是在 Typescript 中,类型会跟随对象字面量,所以它是:

     ({ component: Component, ...rest }: { component: Component, rest: any })
    

    所以实际上第一个Component 是解构变量的名称,而第二个Component 类型component 作为一个组件。我会明确地将内部变量重命名为更有意义的名称并防止出现阴影:

     ({ component: ChildComponent, ...rest }) => (
       //...
       <ChildComponent {...props} />
    )
    

    等于:

     props => {
      const ChildComponent = props.component,
          rest = props;
    
      return <ChildComponent {...rest}/>
     };
    

    如果这是一个对象,这是否意味着该函数正在为其自己的参数分配一个默认的空组件对象?

    不,默认值将跟随 =,例如:

     ({ component: ChildComponent = DefaultComponent, ...rest }) =>
    

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 2012-09-30
      • 2011-11-18
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      相关资源
      最近更新 更多