在 React 开发中,组件和状态管理是两个核心概念。本文将简要介绍 React 组件及其状态管理。

组件

React 组件是 React 应用程序的基本构建块。组件可以是一个类或者一个函数,它们接收输入(props)并返回 React 元素。

类组件

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

函数组件

function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

状态管理

状态是组件的一个属性,它包含组件需要存储的数据。在 React 中,你可以使用 useState 钩子来管理状态。

使用 useState

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

更多内容

想了解更多关于 React 组件和状态管理的知识?请访问我们的 React 教程

React Components