乐趣区

关于react.js:Day-38100-React-Hook之useState基本用法

(一)需要

最近在学习 React,学到了 React Hook 做了 useState Demo。

(二)介绍

1、默认值是数字类型

const [num, setNum] = useState(0);
const clickX = () => {setNum(num + 1);
}

<p>
    1、初始化为数字:{num}
</p>
<Button onClick={clickX}>
    Click Number
</Button>

2、默认值是对象类型

初始化为对象是用构造复制的模式

const [obj, setObj] = useState({a: 1});
const clickObj = () => {setNum(num + 1);
  setObj({...obj, b: num + 1});
}

<p>
    2、初始化为对象: a-{obj.a} ;b-{obj.b}
</p>
<Button onClick={clickObj}>
    Click Object
</Button>

(三)实现 Demo

/*
 * @Author: ArdenZhao
 * @Date: 2022-04-14 16:46:18
 * @LastEditTime: 2022-04-14 17:06:55
 * @FilePath: /react-ts/src/components/react/7-Hook-useState.js
 * @Description: file information
 */
import React, {useState, useCallback} from 'react';
import {Button} from 'antd';
import "antd/dist/antd.css";

function HookUseState(props) {
  // useState 不能放在函数外部,这里设置初始值为 0
  const [num, setNum] = useState(0);
  const [obj, setObj] = useState({a: 1});
  const clickX = () => {setNum(num + 1);
  }
  const clickObj = () => {setNum(num + 1);
    setObj({...obj, b: num + 1});
  }
  return (
    <div>
      <h1>Learn, {props.name}</h1>
      <p>
        1、初始化为数字:{num}
      </p>
      <Button onClick={clickX}>
        Click Number
      </Button>
      <p>
        2、初始化为对象: a-{obj.a} ;b-{obj.b}
      </p>
      <Button onClick={clickObj}>
        Click Object
      </Button>
    </div>
  );
}
export default HookUseState

// 参考链接
// https://flaviocopes.com/react-hook-usecallback/

写在最初的话

学习路上,经常会懈怠。

《有想学技术须要监督的同学嘛~》
https://mp.weixin.qq.com/s/Fy…

如果有须要的搭档,能够加我微信:learningisconnecting
或者能够关注我的公众号:国星聊成长(我会分享成长的办法)

退出移动版