日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

React as a UI Runtime(四、条件)

發布時間:2025/3/20 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 React as a UI Runtime(四、条件) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果React在更新中只重用與元素類型相匹配的宿主實例,那按渲染條件選擇的內容怎么辦呢?
正如下面的代碼,假如我們開始至需要一個input,但稍后需要在它之前渲染一個message : // 第一次渲染 ReactDOM.render(<dialog><input /></dialog>,domContainer );// 第二次渲染 ReactDOM.render(<dialog><p>I was just added here!</p><input /></dialog>,domContainer );

在這個例子中,<input>宿主實例將會被重建。React會遍歷元素樹,并與之前的版本比較:

  • dialog → dialog: 可以重復使用嗎? 可以-type匹配。
  • input → p:可以重復使用嗎?不行,type已經改變了!需要刪除存在的input,并創建新的p宿主實例。
  • (nothing) → input: 需要新建一個input宿主實例。

React這樣的代碼是如下的:

let oldInputNode = dialogNode.firstChild; dialogNode.removeChild(oldInputNode);let pNode = document.createElement('p'); pNode.textContent = 'I was just added here!'; dialogNode.appendChild(pNode);let newInputNode = document.createElement('input'); dialogNode.appendChild(newInputNode);

這不是一種好的更新方式,因為原則上input并沒有被p替代-它僅僅是移動了。我們不想要因為重新創建Dom元素而失去它的選中狀態,聚焦狀態和顯示內容。
幸好這個問題有一個簡單的修復方式,他并不在React應用中常見。
在實踐中,你很少會直接調用ReactDOM.render,實際上,React app常常會拆分成像下面這樣的函數:

function Form({ showMessage }) {let message = null;if (showMessage) {message = <p>I was just added here!</p>;}return (<dialog>{message}<input /></dialog>); }

This example doesn’t suffer from the problem we just described. It might be easier to see why if we use object notation instead of JSX. Look at the dialog child element tree:
這個例子并不會有我們之前描述的那個問題,如果我們使用對象來代替JSX描述會更加明顯,下面是dialog子元素樹:

function Form({ showMessage }) {let message = null;if (showMessage) {message = {type: 'p',props: { children: 'I was just added here!' }};}return {type: 'dialog',props: {children: [message,{ type: 'input', props: {} }]}}; }

function Form({ showMessage }) {
let message = null;
if (showMessage) {

message = {type: 'p',props: { children: 'I was just added here!' } };

}
return {

type: 'dialog', props: {children: [message,{ type: 'input', props: {} }] }

};
}

不管showMessage 是true的還是false,<input>是第二個子元素,并且在render中不會改變它的位置。
如果showMessage 從false變為true,React會遍歷元素樹,并與之前的版本相比較:

  • dialog → dialog:可以重復使用嗎? 可以-type匹配。
  • (null) → p:需要插入一個新的p宿主實例。
  • input → input: 可以重復使用嗎? 可以-type匹配。

那么React會執行類似于下面的代碼:

let inputNode = dialogNode.firstChild; let pNode = document.createElement('p'); pNode.textContent = 'I was just added here!'; dialogNode.insertBefore(pNode, inputNode);

input的狀態并不會改變

總結

以上是生活随笔為你收集整理的React as a UI Runtime(四、条件)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。