Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

React Hooks


Hooks 在 React 16.8 版本中添加。

Hooks 允许函数组件访问状态和其他 React 特性。因此,通常不再需要类组件。

尽管 Hooks 通常取代类组件,但 React 并没有计划移除类。


什么是 Hook?

Hooks 允许我们“钩住”React 的特性,例如状态和生命周期方法。

示例

这是一个 Hook 的示例。如果看不懂没关系,我们将在下一节中详细讲解。

import React, { useState } from "react";
import ReactDOM from "react-dom/client";

function FavoriteColor() {
  const [color, setColor] = useState("red");

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")}
      >Blue</button>
      <button
        type="button"
        onClick={() => setColor("red")}
      >Red</button>
      <button
        type="button"
        onClick={() => setColor("pink")}
      >Pink</button>
      <button
        type="button"
        onClick={() => setColor("green")}
      >Green</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

运行示例 »

您必须从 reactimport Hooks。

这里我们使用 useState Hook 来跟踪应用程序状态。

状态通常指的是需要跟踪的应用程序数据或属性。


Hook 规则

Hooks 有 3 条规则

  • Hooks 只能在 React 函数组件内部调用。
  • Hooks 只能在组件的顶层调用。
  • Hooks 不能是条件性的

注意:Hooks 无法在 React 类组件中使用。


自定义 Hooks

如果您有一些需要在多个组件中重用的状态逻辑,您可以构建自己的自定义 Hooks。

我们将在自定义 Hooks 部分中详细讲解。


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.