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);