React Hooks: useState

hook 是个函数。
使用 react hook 可以利用 react 的功能:例如 state 或 lifecycle 方法。
react 有若干内建的 hook 函数,用户也可以自定义 hook 函数。
react 组件有两种:基于类的组件,以及无状态 stateless 函数组件。但是使用 hook,函数就有可能是有状态的。

hook 函数 useState

以下的例子,用3个button : + - reset 改变数字,并使用 input 修改文字值,使用两次 useState,分别跟踪 count 和 text:

index.js:

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

import reportWebVitals from "./reportWebVitals";

const App = (props) => {
  // count, setCount 理论上可以任意命名
  // 不同于类组件,函数组件中的state不需要是一个对象
  const [count, setCount] = useState(props.count);
  const [text, setText] = useState("");
  return (
    <div>
      <p> The current {text || "count"} is {count} </p>
      <button onClick={() => setCount(count + 1)}>+1</button>
      <button onClick={() => setCount(count - 1)}>-1</button>
      <button onClick={() => setCount(props.count)}>reset</button>
      <input value={text} onChange={(e) => setText(e.target.value)} />
    </div>
  );
};
// 组件默认props
App.defaultProps = {
  count: 0,
};

ReactDOM.render(
  <React.StrictMode>
    <App count={3} />
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

useState 返回值是一个带有两个元素是数组,第1个元素是当前状态值,第2个是用来更新 state 的函数。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值