1. 組件
React 的特點之一就是組件化,組件是用來實現特定或局部功能效果的代碼集合(html/css/js),在我們編寫一個頁面時,往往可以將不同部位進行拆分,拆分的部分就稱爲組件。
同樣的,組件拆分也可以複用代碼,簡化項目編碼,提高運行效率。
2. 自定義組件的兩種方式
React 中組件有兩種方式,分別爲工廠函數組件
和ES6 類組件
。
下面分別使用這兩種方式定義組件,並向頁面輸出元素。
<!-- ... -->
<div id="example1"></div>
<div id="example2"></div>
<script type="text/javascript" src="../build/react.development.js"></script>
<script type="text/javascript" src="../build/react-dom.development.js"></script>
<script type="text/javascript" src="../build/babel.min.js"></script>
<script type="text/babel">
// 1. 定義組件
// 方式1: 工廠函數組件(簡單組件)
function MyComponent() {
return <h2>工廠函數組(簡單組件)</h2>
}
// 方式2: ES6類組件(複雜組件)
class MyComponent2 extends React.Component {
render () {
console.log(this)
return <h2>ES6類組件(複雜組件)</h2>
}
}
// 2. 渲染組件標籤
ReactDOM.render(<MyComponent />, document.getElementById('example1'))
ReactDOM.render(<MyComponent2 />, document.getElementById('example2'))
</script>
<!-- ... -->
上面的兩種方式向頁面輸出了數據:
在自定義組件時,需要注意下面的幾點:
- 組件名必須首字母大寫
- 虛擬 DOM 元素只能有一個根元素
- 虛擬 DOM 元素必須有結束標籤
3. 源碼
本次文章源代碼地址:https://github.com/Mayandev/react-tutorial/blob/master/code/react-component/react-component.html