添加React到网站时,我如何在功能组件中使用钩子?



我想在react网站中使用一个useffect, useState和其他钩子,而不是用node构建。我该怎么做呢?

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

一个功能组件的例子:

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为变量state。setCount是更新状态的方式,0是默认赋值。

最新更新