React 組件(Component) 也是一種元素Element,只不過是粒度更大一些的、包含更多子項目。
通過React組件,把一些相關的元素組織起來,形成可以複用的、有多個成員的元素的組合。 舉例
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>React Components</title></head><body><!-- Target Container --><div id="react-container"></div><!-- React Library & React DOM--><script src="https://unpkg.com/react@16/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script><script> class foodList extends React.Component { render() { return React.createElement("ul", {"className": "food-list"}, React.createElement("li", null, "1 apple"), React.createElement("li", null, "1 banana"), React.createElement("li", null, "2 oranges"), React.createElement("li", null, "2 tomatos") ) } } const list = React.createElement(foodList, null, null) ReactDOM.render( list, document.getElementById('react-container') )</script></body></html>
1、通過繼承 React.Component 建立組件
class foodList extends React.Component {}
2、組件中必須包括render函數
class foodList extends React.Component { render() { // 建立元素的代碼 }}
3、在render中返回一個元素包含多個子項目的組合
render() { return React.createElement( "ul", {"className": "food-list"}, React.createElement("li", null, "1 apple"), React.createElement("li", null, "1 banana"), React.createElement("li", null, "2 oranges"), React.createElement("li", null, "2 tomatos") )}
4、通過createElement 傳入 component foodList 作為參數建立 list 元素
const list = React.createElement(foodList, null, null)
5、渲染
ReactDOM.render( list, document.getElementById('react-container') )