【问题标题】:How can i use hooks in functional component when adding React to a Website?将 React 添加到网站时,如何在功能组件中使用钩子?
【发布时间】:2021-06-02 22:34:15
【问题描述】:

我想在不是用 node 构建的 react 网站中使用 useEffect、useState 和其他钩子。我该如何执行以下操作:

1.How can i use a functional component when adding React to a Website?

2. How can i use hooks in functional component when adding React to a Website?

我不想使用这里引用的基于类的组件https://reactjs.org/docs/add-react-to-a-website.html

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    功能组件示例:

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

    以及如何在另一个功能组件中调用它:

    function App() {
      return (
        <div>
          <Welcome name="Sara" />
          <Welcome name="Cahal" />
          <Welcome name="Edite" />
        </div>
      );
    }
    

    对于钩子,最常用的钩子是 useState 钩子。

    你需要先导入:

    import React, { useState } from 'react';
    

    并在组件中使用它来创建和更改变量的值。

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

    count 是一个称为状态的变量。 setCount 是您更新该状态的方式,0 是默认分配值。

    【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2021-04-13
    • 2020-11-29
    • 1970-01-01
    • 2021-08-11
    • 2019-12-08
    • 2016-04-17
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多