React 中的类组件和函数组件是两种不同的组件编写方式,它们之间有一些区别。
语法和写法:类组件是使用类的语法进行定义的,它继承自 React.Component 类,并且需要实现 render() 方法来返回组件的 JSX。函数组件是使用函数的语法进行定义的,它接收一个 props 对象作为参数,并返回组件的 JSX。
示例:类组件
- class MyComponent extends React.Component {
- render() {
- return Hello, {this.props.name};
- }
- }
示例:函数组件
- function MyComponent(props) {
- return <div>Hello, {props.name}</div>;
- }
状态管理:在类组件中,可以使用 state 属性来存储和管理组件的内部状态。state 是一个可变的对象,当状态发生变化时,组件会重新渲染。函数组件在 React 16.8 引入的 Hooks 特性后,也可以使用 useState Hook 来管理组件的状态。 示例:类组件中的状态管理
- class Counter extends React.Component {
- constructor(props) {
- super(props);
- this.state = { count: 0 };
- }
-
- increment() {
- this.setState({ count: this.state.count + 1 });
- }
-
- render() {
- return (
- <div>
- Count: {this.state.count}
- <button onClick={() => this.increment()}>Increment</button>
- </div>
- );
- }
- }
示例:函数组件中的状态管理(使用 useState Hook)
- function Counter() {
- const [count, setCount] = React.useState(0);
-
- const increment = () => {
- setCount(count + 1);
- };
-
- return (
- <div>
- Count: {count}
- <button onClick={increment}>Increment</button>
- </div>
- );
- }
示例:函数组件中的生命周期模拟(使用 useEffect Hook)
- function MyComponent(props) {
- React.useEffect(() => {
- console.log('Component mounted');
-
- return () => {
- console.log('Component will unmount');
- };
- }, []);
-
- React.useEffect(() => {
- console.log('Component updated');
- });
-
- return <div>Hello, {props.name}</div>;
- }
总的来说,类组件和函数组件都可以实现相同的功能,但随着 React 的发展,函数组件在代码简洁性、可测试性和性能方面具有一些优势,并且在使用 Hooks 后,函数组件可以更方便地处理状态和副作用。因此,函数组件逐渐成为 React 中的主要编写方式。
