React是一個library,所以開發上會用到一些相依套件來開發甚至是優化開發體驗,要更認識React的運作原理的話,我推薦可以利用一些閒暇時間去更了解Create React App一開始的內容。因為一開始產生的專案最原始最單純,你也可以找相依的套件去查看source code背後做了哪些事情。

Vanilla.js如何更新DOM

透過DOM API可以更新與操作DOM結構,更白話的講就是CRUD。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const root = document.querySelector( 'body' );

function createListElement() {
const libsAndFrameworksNames = ['React.js', 'Angular', 'Vue.js',
'Node.js', 'Underscore.js'];

const ul = document.createElement( 'ul' );
ul.classList.add( "list-lib-frameworks" );

libsAndFrameworksNames.forEach( function appoendToUnorderedList( name ) {
const listElement = document.createElement( 'li' );
listElement.innerText = name;
ul.appendChild( listElement );
} );

return ul;
}

function createWebPageWithJavaScript( root ) {
// PARENT ELEMENT
const parent = document.createElement( 'section' );
parent.classList.add( 'js-section' );

// HEADING ELEMENT
const heading = document.createElement( 'h1' );
heading.innerText = 'JavaScript Libraries and Frameworks';

// UNORDERED LIST ELEMENT
const unorderedListElement = createListElement();

// APPEND HEADDING AND UNORDERED LIST ELEMENT TO PARENT
parent.appendChild(heading)
parent.appendChild( unorderedListElement );

// APPEND PARENT TO ROOT ELEMENT
root.appendChild( parent );
}

createWebPageWithJavaScript( root );

但是隨著專案的壯大,相信你應該也不會想要繼續寫這麼一大坨程式了,因此你會尋求其他人幫你封裝好的套件來使用。
像是React就提供了DOM互動的解決方案,你只需要告訴React你要update哪部分的DOM,並且針對element進行render或recociling。

產生element

React element是描述DOM的最小單位
產生的方式如下:

1
React.createElement(type, [props], [...children]);

由好幾個element組合之後,就會形成一個樹狀結構,我們稱為Virtual DOM tree。

如果說你想要產生這個element:

1
<li> React.js </li>

那麼你會這樣寫:

1
2
3
4
5
const listElement = React.createElement( 'li', {
className: 'list'
}, 'React.js' );

console.log( listElement );

不過React DOM他是一個中介的東西,所以單純給JS讀取是看不懂的
所以要調用React DOM的render

1
2
3
4
5
const listElement = React.createElement( 'li', {
className: 'list'
}, 'React.js' );

ReactDOM.render( listElement, document.querySelector( '#root' ) );

React建議開發者加入unique key,這樣可以大大優化渲染的效能(可以參考我之前寫的文章)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const listOfLibAndFrameworks = ['React.js', 'Angular', 'Vue.js',
'Node.js', 'underscore.js'];

const mainReactElement = React.createElement(
"section",
{ className: "js-section" },
React.createElement( "h1", null, "JavaScript Libraries and Frameworks" ),
React.createElement(
"ul",
{ className: 'list-lib-frameworks' },
listOfLibAndFrameworks.map((element, index) => React.createElement('li',
{ key: index }, element))
)
);

console.log( mainReactElement );

ReactDOM.render(mainReactElement, document.querySelector( '#root' ));

React透過react-dom這個套件來進行render

參考資料

React DOM
React源码剖析:react、 react-dom、react-reconciler 的关系


Comment