本文共 1356 字,大约阅读时间需要 4 分钟。
react钩子
Check out my first, if you’re new to them.
如果您是新手,请先查看我的 。
One React hook I most often use is useState
.
我最常使用的一个React钩子是useState
。
import React, { useState } from 'react'
Using the useState()
API, you can create a new state variable, and have a way to alter it. useState()
accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state. Since it returns an array we use to access each individual item, like this: const [count, setCount] = useState(0)
使用useState()
API,您可以创建一个新的状态变量,并可以更改它。 useState()
接受状态项的初始值,并返回一个包含状态变量的数组,以及一个用来更改状态的函数。 因为它返回一个数组,所以我们使用来访问每个单独的项,如下所示: const [count, setCount] = useState(0)
Here’s a practical example:
这是一个实际的例子:
import { useState } from 'react'const Counter = () => { const [count, setCount] = useState(0) return ()}ReactDOM.render(You clicked {count} times
, document.getElementById('app'))
You can add as many useState()
calls you want, to create as many state variables as you want. Just make sure you call it in the top level of a component (not in an if
or in any other block).
您可以添加useState()
调用,以创建useState()
状态变量。 只要确保在组件的顶层(而不是if
或任何其他块中)调用它即可。
Example on Codepen:
Codepen上的示例:
See the Pen by Flavio Copes () on .
见笔由弗拉维奥COPES( 上) 。
翻译自:
react钩子
转载地址:http://thqgb.baihongyu.com/