react 組件引用組件_React Elements VS React組件

react 組件引用組件

A few months ago I posted to Twitter what I thought was a simple question:

幾個月前,我在Twitter上發布了一個我認為簡單的問題:

What surprised me wasn’t the joint confusion around this question, but rather the amount of inaccurate responses I received.

讓我感到驚訝的不是關于這個問題的共同困惑,而是我收到的不準確的答復。

Instances / Instantiation

實例/實例化

Instances / Instantiation Rendering

實例/實例化 渲染

Instances / Instantiation RenderingEvaluation

實例/實例化 渲染 評估

Instances / Instantiation RenderingEvaluationInvocation

實例/實例化 渲染 評估 調用

Instances / Instantiation RenderingEvaluationInvocation“Using it :)”

實例/實例化 渲染 評估 調用 “使用它:)”

The primary reason for the confusion is that there’s an often un-talked about abstraction layer between JSX and what’s actually going on in React land. In order to answer this question, we need to take a deep dive into that abstraction.

造成混淆的主要原因是,在JSX與React領域中實際發生的事情之間經常沒有談論抽象層。 為了回答這個問題,我們需要深入研究該抽象。

Let’s start by looking at the absolute fundamentals of React.

讓我們從了解React的絕對基礎開始。

React到底是什么? (What exactly is React?)

React is a library for building user interfaces. No matter how complex React or the React ecosystem seem to be, this is React at its core — building UIs. With this in mind, we arrive at our first definition, an Element.

React是用于構建用戶界面的庫。 無論React或React生態系統看起來多么復雜,這都是React的核心-構建UI。 考慮到這一點,我們得出了第一個定義, Element

Simply put, a React element describes what you want to see on the screen.

簡而言之, React元素描述了您想要在屏幕上看到的內容

Not so simply put, a React element is an object representation of a DOM node.

簡而言之, React元素是DOM節點的對象表示

Notice that I used the word describe. It’s important to note that a React element isn’t actually the thing you’ll see on your screen, instead, it’s just an object representation of it. There are a few reasons for this:

注意,我使用了describe這個詞。 重要的是要注意,React元素實際上并不是您將在屏幕上看到的東西,而是它的對象表示。 這有幾個原因:

  1. JavaScript objects are lightweight. React can create and destroy these elements without too much overhead.

    JavaScript對象是輕量級的。 React可以創建和銷毀這些元素,而無需太多開銷。
  2. React is able to analyze the object, then analyze the actual DOM, and then update the actual DOM only where a change occurred. This has some performance upsides to it.

    React能夠分析對象,然后分析實際DOM,然后僅在發生更改的地方更新實際DOM。 這具有一些性能優勢。

In order to create our object representation of a DOM node (aka React element), we can use React’s createElement method.

為了創建我們的DOM節點(又名React元素)的對象表示,我們可以使用React的createElement方法。

const element = React.createElement(   'div',   {id: 'login-btn'},   'Login')

createElement takes in three arguments:

createElement接受三個參數:

  1. a tag name string (div, span, etc.)

    標簽名稱字符串(div,span等)
  2. any attributes you want the element to have

    您希望元素具有的任何屬性
  3. contents or the children of the element — in this case the text “Login”.

    元素的內容或子元素-在這種情況下為“登錄”文本。

The createElement invocation above is going to return an object with this shape:

上面的createElement調用將返回具有以下形狀的對象:

{   type: 'div',   props: {     children: 'Login',     id: 'login-btn'   } }

And when it’s rendered to the DOM (using ReactDOM.render), we’ll have a new DOM node that looks like this:

當將其渲染到DOM時(使用ReactDOM.render),我們將擁有一個新的DOM節點,如下所示:

<div id='login-btn'>Login</div>

So far, so good. What’s interesting about learning React is that typically the first thing you’re taught is components. “Components are the building blocks of React.”

到目前為止,一切都很好。 學習React的有趣之處在于,通常您首先要學習的是組件。 “組件是React的基石。”

Notice, however, that we started this post with elements. The reason for this is because once you understand elements, understanding components is a smooth transition.

但是請注意,我們是從元素開始的。 這樣做的原因是,一旦您理解了元素,理解組件就是一個平穩的過渡。

A component is a function or a Class which optionally accepts input and returns a React element.

組件是可以選擇接受輸入并返回React元素的函數或類。

function Button ({ onLogin }) {   return React.createElement(     'div',     {id: 'login-btn', onClick: onLogin},     'Login'   )}

By definition, we have a Button component which accepts an onLogin input and returns a React element. One thing to note is that our Button component receives an onLogin method as its prop. To pass that along to our object representation of the DOM, we pass it along as the second argument to createElement, just as we did our id attribute.

根據定義,我們有一個Button組件,它接受一個onLogin輸入并返回一個React元素。 需要注意的一件事是,我們的Button組件接收一個onLogin方法作為其支持。 要將其傳遞給我們的DOM對象表示,我們將其作為createElement的第二個參數傳遞,就像我們的id屬性一樣。

Let’s go deeper.

讓我們更深入。

Up until this point we’ve only covered creating React elements with the “type” property of native HTML elements (“span”, “div”, etc), but you can also pass in other React components to the first argument of createElement.

到目前為止,我們僅介紹了使用本機HTML元素(“ span”,“ div”等)的“ type”屬性創建React元素的方法,但是您也可以將其他React組件傳遞給createElement的第一個參數。

const element = React.createElement(  User,   {name: 'Tyler McGinnis'},  null )

However, unlike with an HTML tag name, if React sees a class or a function as the first argument, it will then check to see what element it renders, given the corresponding props. React will continue to do this until there are no more createElement invocations which have a class or a function as their first argument. Let’s take a look at this in action.

但是,與HTML標簽名稱不同的是,如果React將類或函數作為第一個參數,它將在給定相應道具的情況下檢查其呈現的元素。 React將繼續執行此操作,直到不再有將類或函數作為其第一個參數的createElement調用為止。 讓我們看看實際情況。

function Button ({ addFriend }) {  return React.createElement(    "button",     { onClick: addFriend },     "Add Friend"   ) }
function User({ name, addFriend }) {   return React.createElement(    "div",     null,    React.createElement( "p", null, name ),    React.createElement(Button, { addFriend })  ) }

Above we have two components. A Button and a User. User’s object representation of the DOM will be a “div” with two children, a “p” which wraps the user’s name and a Button component. Now let’s swap out the createElement invocations with what they return,

上面我們有兩個部分。 一個按鈕和一個用戶。 DOM的用戶對象表示形式將是帶有兩個子元素的“ div”,其中包含用戶名的“ p”和一個Button組件。 現在,讓我們將createElement調用與返回的內容交換出去,

function Button ({ addFriend }) {   return {     type: 'button',     props: {       onClick: addFriend,       children: 'Add Friend'     }   } }
function User ({ name, addFriend }) {   return {     type: 'div',     props: {       children: [{         type: 'p',        props: { children: name }       },       {        type: Button,        props: { addFriend }       }]    }  }}

You’ll notice in the above code we have four different type properties, “button”, “div”, “p”, and Button. When React sees an element with a function or class type (like our “type: Button” above), it will then consult with that component to know which element it returns, given the corresponding props.

您會在上面的代碼中注意到我們有四個不同的類型屬性,即“按鈕”,“ div”,“ p”和“按鈕”。 當React看到一個具有函數或類類型的元素(例如上面的“type: Button” )時,它會與該組件進行協商以知道它返回了哪個元素,并給出了相應的道具。

With that in mind, at the end of this process, React has a full object representation of the DOM tree. In our example, that will look like this:

考慮到這一點,在此過程結束時,React具有DOM樹的完整對象表示形式。 在我們的示例中,將如下所示:

{  type: 'div',   props: {    children: [{      type: 'p',      props: { children: 'Tyler McGinnis' }    },     {       type: 'button',       props: {         onClick: addFriend,         children: 'Add Friend'      }     }]   } }

This whole process is called reconciliation in React and it’s triggered every time setState or ReactDOM.render are called.

這整個過程在React中稱為對帳,每次調用setStateReactDOM.render都會觸發。

So now let’s again take a look at our initial question that sparked this blog post:

現在,讓我們再次看一下引發此博客文章的最初問題:

At this point we have all the knowledge we need to answer this question, except for one important piece.

至此,我們已經掌握了回答這一問題所需的全部知識,但其中一項重要內容除外。

Odds are if you’ve been using React for any amount of time, you don’t use React.createElement to create your object representations of the DOM. Instead, you probably use JSX.

奇怪的是,如果您已經使用React一段時間,那么就不要使用React.createElement來創建DOM的對象表示形式。 相反,您可能使用JSX。

Earlier I wrote: “The primary reason for the confusion is that there’s an often un-talked about abstraction layer between JSX and what’s actually going on in React land.” This abstraction layer is that JSX is always going to get transpiled to React.createElement invocations, typically via Babel.

早些時候我寫道:“造成混淆的主要原因是,JSX與React領域實際發生的事情之間經常沒有談論抽象層。” 這個抽象層是JSX通常總是 通過Babel 轉換為 React.createElement 調用

Looking at our earlier example, this code:

看我們前面的例子,這段代碼:

function Button ({ addFriend }) {  return React.createElement(    "button",    { onClick: addFriend },    "Add Friend"    )}
function User({ name, addFriend }) {   return React.createElement(    "div",    null,    React.createElement( "p", null, name),    React.createElement(Button, { addFriend })  )}

is the result of this JSX being transpiled.

是此JSX被編譯的結果。

function Button ({ addFriend }) {   return (     <button onClick={addFriend}>Add Friend</button>   )}
function User ({ name, addFriend }) {  return (     <div>     <p>{name}</p>     <Button addFriend={addFriend}/>    </div>  )}

So finally, what do we call it when we write out our component like this, <Icon/>?

所以最后,當我們寫出這樣的組件<Ico n />時,我們怎么稱呼它?

We can call it “creating an element” because after the JSX is transpiled, that’s exactly what’s happening.

我們可以稱其為“創建元素”,因為在JSX編譯之后,這就是正在發生的事情。

React.createElement(Icon, null)

All of these examples, are “creating an React element”

所有這些示例都是“創建React元素”

React.createElement(  'div',   className: 'container',   'Hello!')
<div className='container'>Hello!</div&gt; <Hello />

Thanks for reading! For more on this subject, read React Components, Instances, and Elements by Dan Abramov.

謝謝閱讀! 有關此主題的更多信息,請閱讀Dan Abramov的React組件,實例和元素 。

Follow Tyler McGinnis on Twitter ??Originally published at tylermcginnis.com.

在Twitter上關注Tyler McGinnis?? 最初發布于tylermcginnis.com 。

翻譯自: https://www.freecodecamp.org/news/react-elements-vs-react-components-fdc776705880/

react 組件引用組件

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/396071.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396071.shtml
英文地址,請注明出處:http://en.pswp.cn/news/396071.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

appium 環境搭建(不推薦安裝此版本appium,推薦安裝appium desktop)

一&#xff1a;安裝node.js 1、雙擊這個軟件 2、一鍵安裝&#xff0c;全都下一步&#xff0c;不要私自更改安裝路徑 3、打開cmd&#xff0c;輸入npm&#xff0c;出現如下截圖表示成功 二&#xff1a;安裝appium 1、雙擊appium-installer.exe 2、一鍵安裝&#xff0c;全都下一步…

二級c語言上機題庫及解析,2013年計算機二級C語言上機題庫及答案解析(3)

填空題給定程序中&#xff0c;函數fun的功能是:在形參ss所指字符串數組中&#xff0c;查找含有形參substr所指子串的所有字符串并輸出&#xff0c;若沒找到則輸出相應信息。ss所指字符串數組中共有N個字符串&#xff0c;且串長小于M。程序中庫函數strstr(s1, s2)的功能是在 s1串…

js 數組遍歷符合條件跳出循環體_C++模擬面試:從數組“緊湊”操作說開來

面試官自來也去掉一個字符串中的空格。假設用C語言來解答&#xff0c;字符串是char數組。O(n)時間復雜度實現不難&#xff0c;比如額外申請一個新數組&#xff0c;然后遍歷一遍字符串&#xff0c;將符合條件的字符存儲到新數組中&#xff0c;實現起來很簡單。但這顯然不能讓面試…

項目NABCD的分析

N&#xff1a;你的創意解決了用戶的什么需求 本項目解決了在校大學生和社會工程人士在計算一些工程測量中的需求&#xff0c; 可以通過自己提供的一些測得的已知數據來推算出自己想要的數據結果&#xff0c; 比用戶自己手動計算更有效更快更節省時間 A&#xff1a;有什么招數來…

git 命令git 地址_這是我上周使用的所有Git命令及其作用。

git 命令git 地址by Sam Corcos由Sam Corcos 這是我上周使用的所有Git命令及其作用。 (Here are all the Git commands I used last week, and what they do.) Like most newbies, I started out searching StackOverflow for Git commands, then copy-pasting answers, witho…

兩個隊列實現一個棧思路c語言,兩個棧實現隊列功能C語言實現能運行!

#include#includetypedef struct sq{char *ps;int top;int Maxsize;}stack;void initstack(stack *s,int ms){s->ps(char*)malloc(ms*sizeof(char));s->top-1;s->Maxsizems;};void push(stack *s,char val){if(s->tops->Maxsize-1){printf("棧已滿\n"…

基本入門程序編寫格式和注意事項

在安裝好JDK后聯系程序的基本寫法。1、先創建記事本&#xff0c;如果有超級記事本如:notepad、ultraedit、editplus等更好。重命名把記事本后面的后綴名改為.java 但是值得注意的是要看看自己創建的記事本文檔是否是隱藏后綴名的。要是有設置隱藏的就取消隱藏&#xff0c;以免混…

.dll文件存在但是不顯示_一招巧妙解決U盤內文件明明存在,打開U盤而內容卻不顯示的問題...

大家可能都遇到過這種情況&#xff0c;就是說U盤中明明有文件&#xff0c;但是插在電腦上就是什么文件都沒有&#xff0c;一片空白&#xff0c;這樣的問題對于那些對文件很重要且僅保存了1份的人來說是很.kongbu.&#xff0c;因為U盤中的內容都是命根子。給大家介紹絕對有用的解…

《java入門第一季》之面向對象(包概述)

由于eclipse等ide的強大功能&#xff0c;使得建包&#xff0c;導包用一些快捷鍵就能完成。這里對包的概念做稍微的敘述&#xff0c;了解即可&#xff1a; 分包后使得項目更加清晰&#xff0c;提高代碼維護性。 包&#xff1a; A:其實就是文件夾 B:作用 …

Vue 框架-05-動態綁定 css 樣式

Vue 框架-05-動態綁定 css 樣式 今天的小實例是關于 Vue 框架動態綁定 css 樣式&#xff0c;這也是非常常用的一個部分 首先說一下 動態綁定&#xff0c;相對的大家都知道靜態綁定&#xff0c;靜態綁定的話&#xff0c;直接加 class“”就可以了&#xff0c;使用 Vue 呢之前也介…

ember.js_如何設置基本的Ember.js應用

ember.jsby Tracy Lee | ladyleet特雷西李(Tracy Lee)| Ladyleet 如何設置基本的Ember.js應用 (How to set up a Basic Ember.js app) So, you want to test out Ember, eh? This article will walk through building a basic app.所以&#xff0c;您想測試Ember&#xff0c;…

分數轉小數C語言,這是把小數轉換成分數的程序,可是輸入0.6666無限循環

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓#include int main(){double a;scanf("%lf", &a);輸入小數int b, c 0, d 0;double b1 a;do{b1 *10;b (int)b1;printf("%d\n", b);if(b%10!0){c;if(d>0){c d;d 0;}}else{d;}}while(d<5);printf("…

arm處理器的歷史及現狀

1 arm處理器的發展歷史 arm1 arm2 arm3 arm6 arm7 arm9 arm11 arm cortex 2 arm處理器現狀 arm cortex A a即application&#xff0c;即應用處理器&#xff0c;主要用在智能手機、平板電腦和服務器上。 arm cortex M m即mcu&#xff0c;即單片機上的處理器&#xff0c;它的特點…

Linq常用List操作總結,ForEach、分頁、交并集、去重、SelectMany等

1 /*2 以下圍繞Person類實現&#xff0c;Person類只有Name和Age兩個屬性3 一.List<T>排序4 1.1 List<T>提供了很多排序方法&#xff0c;sort(),Orderby(),OrderByDescending().5 */6 7 lstPerson lstPerson.OrderByDescending(x>x.Name).ToList(); //降序8 ls…

bool查詢原理 es_ES系列之原理copy_to用好了這么香

寫在前面Elasticsearch(以下簡稱ES)有個copy_to的功能&#xff0c;之前在一個項目中用到&#xff0c;感覺像是發現了一個神器。這個東西并不是像有些人說的是個語法糖。它用好了不但能提高檢索的效率&#xff0c;還可以簡化查詢語句。基本用法介紹直接上示例。先看看mapping&am…

加密算法—MD5、RSA、DES

最近因為要做一個加密的功能&#xff0c;簡單了解了一下加密算法&#xff0c;現在比較常用的有三個加密算法MD5加密算法、RSA加密算法、DES加密算法。 MD5加密算法 定義&#xff1a;MD5算法是將任意長度的“字節串”變換成一個128bit的大整數&#xff0c;并且它是一個不可逆的字…

隨機加密_隨機藝術和加密圣誕樹

隨機加密When I first learned how to code, one of my first tasks was setting up an SSH key so I could use encryption to securely connect to my friend’s Linux server.當我第一次學習如何編碼時&#xff0c;我的第一個任務是設置SSH密鑰&#xff0c;以便可以使用加密…

用c語言編寫一個2048 游戲,求c語言編寫的2048游戲代碼,盡量功能完善一些

正在編寫中&#xff0c;請稍后&#xff01;追答 : 代碼來了&#xff01;有點急&#xff0c;沒做界面。追答 : 2048_launcher。c&#xff1a;#include#include#includevoid main(){printf("正在啟動中&#xff0c;請稍后&#xff01;");Sleep(1000);system("bin\…

MySQL之數據庫對象查看工具mysqlshow

mysqlshow&#xff1a;數據庫對象查看工具&#xff0c;用來快速查找存在哪些數據庫、數據庫中的表、表中的列或索引。選項&#xff1a;--count 顯示數據庫和表的統計信息-k 顯示指定的表中的索引-i 顯示表的狀態信息不帶任何參數顯示所有數據庫[rootwww mys…

軟件工程分組

電子零售系統 陳仔祥 孟拓 陳庚 汪力 郭澳林 崔祥岑 劉校 肖宇 武清 胡圣陽轉載于:https://www.cnblogs.com/2231c/p/9960751.html