簡體   English   中英

沒有TypeScript的情況下,這種類型注釋如何在React代碼中工作?

[英]How is this type annotation working in React code without TypeScript?

我在ReactRouter頁面上看了這個代碼示例 ,這很有趣:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

component: Component部分看起來像類型注釋。 當我將示例放到一個空文件中時,Webstorm並沒有抱怨,但是我沒有看到它們使用Flow或TypeScript或導入中的任何內容。

JavaScript已經有類型注釋了嗎? 當我搜索時,我在MDN上沒有看到任何關於此的信息,而且React也不自動從我學到的內容中提供類型注釋。

這不是類型注釋。 這是一個稱為ES6的功能,可分解剩余參數

首先考慮以下示例:(銷毀分配)

const test = myObject.prop
// prop can be assigned in a variable
const { prop } = myObject
// but we want prop as a test variable
// and can be written as
const { prop: test } = myObject
// which is similar to first line
console.log(test)

這是我們可以傳遞參數的方式:

({ component, ...rest })

// We're giving component name as Component

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

因此,您可以使用<Component />因為您知道小寫組件<component />在react中是無效的。


此外,我建議您深入了解以下博客:

Hackernoon:了解解構任務

JavaScript信息:解構分配

Codeburst:銷毀作業完整指南

Dev.to:解構分配-數組

Dev.to:解構分配-對象

您看到的不是類型注釋,而是對象模式中的屬性。 讓我們簡化您的示例以幫助查看發生了什么。

這是一個易於理解的函數:

f = (h) => [h.x, h.y]

函數f接收對象h並返回包含hxhy的數組。 現在,在現代JavaScript中,不必傳遞對象並將其在函數主體中分開。 取而代之的是,我們將函數的參數部分設置為模式 ,這樣就完全不必理會h變量了。 因此,我們可以像這樣重寫它(與您的示例類似):

f = ({x: xValue, y: yValue}) => [xValue, yValue]

因此,就像以前一樣,您可以將具有x和y屬性的任何對象傳遞給f,它將返回這些屬性處的值的數組。

它在起作用:

> f = (h) => [h.x, h.y]
[Function: f]
> f({x:1, y:2, z:3})
[ 1, 2 ]
> f = ({x: xValue, y: yValue}) => [xValue, yValue]
[Function: f]
> f({x:1, y:2, z:3})
[ 1, 2 ]

xValue yValue ,通常會跳過xValueyValue部分並具有:

f = ({x: x, y: y}) => [x, y]

由於簡寫的屬性表示法,它只是:

f = ({x, y}) => [x, y]

但是正如@BhojendraRauniyar在另一個答案中所寫的那樣,使用此代碼的框架中存在大寫約定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM