react钩子_如何使用useState React钩子

react钩子

Check out my React hooks introduction first, if you’re new to them.

如果您是新手,请先查看我的React hooks简介

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 array destructuring 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 (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  )
}

ReactDOM.render(<Counter />, 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 React Hooks example #1 counter by Flavio Copes (@flaviocopes) on CodePen.

见笔阵营鱼钩示例#1计数器由弗拉维奥COPES( @flaviocopes上) CodePen

翻译自: https://flaviocopes.com/react-hook-usestate/

react钩子

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值