React 學習筆記之定義組件 Component

React 視瀏覽器每一個顯示的項目為一個組件,組件和組件是一層和一層的調用及嵌套關係。要想在介面上顯示你要顯示的資訊,就先要學會組件的定義。

組件是一個獨立的 JavaScript 類,他繼承與 React 的 Component。首先我們要 import React 和 Component 模組。隨後生成一個類繼承 React.Component。並實現一個 render 方法,告訴外界你這個組件繪製了哪些內容。最終在文件底部導出這個模組,提供其他模組導入。

// 偽程式碼  import React, { Component } from 'react';    class CommentBox extends React.Component {    render() {      return (        <div className="ui comments">          .....        </div>      );    }  }    export { CommentBox as default };

在 index.js 中引入我們寫好的模組需要首先 import 我們編寫好的模組。然後直接在 ReactDOM.render 中將我們組件作為第一個參數傳遞即可。

import React from 'react';  import ReactDOM from 'react-dom';  import CommentBox from './comment/CommentBox';    ReactDOM.render(    <CommentBox />,    document.getElementById('root')  );

這樣我們自己定義的組件就可以顯示出來了。

Tags: