React as a UI Runtime(四、条件)
正如下面的代碼,假如我們開始至需要一個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常常會拆分成像下面這樣的函數:
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) {
}
return {
};
}
不管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(四、条件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 脑洞大开的翻转代码
- 下一篇: 虚拟机VMware12下安装window