React 入門 03 - 元素與組件

前言

從 React 入門 02 - JSX 學習了JSX的基本用法,本文我們開始深入探討React 元素與組件。

React 元素

元素是構成React引用的最小磚塊,描述了你在屏幕上想看到的內容。與瀏覽器的 DOM 元素不同,React 元素是創建開銷極小的普通對象。React DOM 會負責更新 DOM 來與 React 元素保持一致。

ReactDOM.render(...) 即用來將一個React元素渲染到Html的DOM根元素。

React 元素是不可變對象。一旦被創建,你就無法更改它的子元素或者屬性。根據我們已有的知識,更新 UI 唯一的方式是創建一個全新的元素,並將其傳入 ReactDOM.render()。React 進行元素更新時會自動將當前元素及其子元素與之前的狀態進行比較,從而只更新改變的地方。

function tick() {
    const element = (
        <div>
            <h1> Hello, React!</h1>
            <h2> It is {new Date().toLocaleString()} </h2>
        </div>
    );

    ReactDOM.render(
        element,
        document.getElementById('root')
    );
}

// 使用定時器,定時調用方法tick,刷新元素element
setInterval(tick, 1000);

element.html Git Hub 🔗 

React 組件

React 允許將代碼封裝成組件(component),然後像插入普通 HTML 標籤一樣,在網頁中插入這個組件。React.createClass 方法就用於生成一個組件類。

React 組件,從概念上類似於 JavaScript 函數。它接受任意的入參(即 “props”),並返回用於描述頁面展示內容的 React 元素。常用定義方法爲函數組件和class組件。

函數組件與 class 組件

// 定義函數組件Welcome, 接收唯一帶有數據的 “props”(代表屬性)對象與並返回一個 React 元素
function Welcome(pros) {
    return <h1> Hello, {pros.name} </h1>;
}

// class 組件
class Hello extends React.Component {
    render() {
        return <h1> Hello, {this.pros.name} </h1>
    }
}

注意: 組件名稱必須以大寫字母開頭。

React 會將以小寫字母開頭的組件視爲原生 DOM 標籤。例如,<div /> 代表 HTML 的 div 標籤,而 <Welcome /> 則代表一個組件,並且需在作用域內使用 Welcome。

 

渲染組件

然後即可使用自定義組件聲明React 元素並渲染。

// 使用React自定義組件 聲明元素 渲染組件
const element =  <div> 
        <Welcome name='Ria'/>
        <Hello name='Ming' />
    </div>;

ReactDOM.render(
    element,
    document.getElementById('root')
);

 component.html Git Hub 🔗

組合組件

組件可以在其輸出中引用其他組件。這就可以讓我們用同一組件來抽象出任意層次的細節。

如下例子所示,Welcome是一個函數組件,Hello是一個class組件。我們組合這兩個組件定義出另一個函數組件 App 並渲染到html頁面。

// 定義函數組件Welcome, 接收唯一帶有數據的 “props”(代表屬性)對象與並返回一個 React 元素
function Welcome(props) {
    return <h1> Hello, {props.name}! </h1>;
}

// class 組件
class Hello extends React.Component {
    render() {
        return <h1> Hello, {this.props.name}! </h1>
    }
}

// 定義一個組合組件
function App() {
    return (
        <div>
            <Welcome name = 'Ria' />
            <Hello name = 'Ming' />
        </div>
    );
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

composite.html Git Hub 🔗

Props 的只讀性

React 組件的props屬性是隻讀的,無論是函數組件還是class組件都不能修改其props。 

參考資源

https://zh-hans.reactjs.org/docs/rendering-elements.html

https://www.ruanyifeng.com/blog/2015/03/react.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章