在 React 中,函數組件和類組件是兩種構建組件的方式,它們在多個方面存在區別,以下詳細介紹:
1. 語法和定義
- 類組件:使用 ES6 的類(class)語法定義,繼承自
React.Component
。需要通過this.props
來訪問傳遞給組件的屬性(props),并且通常要實現render
方法返回 JSX。示例代碼如下:
import React, { Component } from 'react';class Counter extends Component {constructor(props) {super(props);this.state = { count: 0 };}increment = () => {this.setState({ count: this.state.count + 1 });}render() {return (<div><p>計數值: {this.state.count}</p><button onClick={this.increment}>增加</button></div>);}
}export default Counter;
- 函數組件:使用 JavaScript 函數定義,接收
props
作為參數并返回 JSX。在 Rea