[英]reactjs : Diffrence between regular/arrow functions and react functional components
[英]Are React Functional Components Regular Functions or Constructor Functions?
在過去(換句話說,幾年前)React 組件是具有render
方法的類。
class MyComponents extends React.Component {
render() {
return <div>...</div>
}
}
最近,React 引入了函數式組件。
function MyComponent() {
return <div>...</div>
}
以上任何一個都可以讓你在另一個 JSX 中使用你的組件——像這樣
<Navigation>
<MyComponent/>
</Navigation>
我想知道,在幕后,React 是使用這些功能組件函數作為 object 構造函數,還是只是將組件 function 作為常規 ZC1C425268E68385D1AB5074C17A94F1 調用。
也就是說——你可以調用 javascript function
function someFunction() {
//...
}
const result = someFunction()
或者,您可以使用 javascript function 創建一個新的 object
function SomeFunction() {
//...
}
const object = new SomeFunction()
In plain javascript the convention is usually that a function that's Capitalized
is a constructor function, and function that's not is a regular function. 然而,我讀到的很多關於組件的淺薄博客文章都表明(但從來沒有直接提到 state)這些組件函數被用作常規函數,而不是object 構造函數。
這里有誰知道函數組件是 object 構造函數、常規函數,還是 React 在幕后做了第三件奇怪的事情。 如果你能指出 React 內部代碼中執行此操作的特定位,則可以加分。
好的,我想我已經最終找到了這個。 功能組件不作為構造函數調用——它們只是作為常規 function 調用。
首先——如果我向組件添加一些調試
function MyComponent() {
/* ... */
console.log(this)
/* ... */
}
this
的值是未定義的。 這與將MyComponent
調用為 function 的代碼一致。 如果代碼調用new MyComponent
, this
將是MyComponent
object 的一個實例。
其次,如果我正確地閱讀了源代碼,看起來這個條件是 React 具有處理基於類和基於函數的組件的分支邏輯的一個地方。
基於 class 的組件得到new
的處理,但基於 function 的組件沒有。
if (isClass) {
inst = new Component(element.props, publicContext, updater);
/*...*/
} else {
/* ... */
inst = Component(element.props, publicContext, updater);
/* ... */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.