-
作用:在函数组件中使用state以及其他的React特性
-
常用的hook:React.useState()、React.useEffect()、React.useRef()
案例:
-
类组件实现代码
javascriptimport React, { Component } from 'react' import { root } from '../../index' export default class countClass extends Component { state = { count: 0 } myRef = React.createRef() componentDidMount(){ this.timer = setInterval(()=>{ this.setState(state => ({count:state.count+1})) },1000) } componentWillUnmount(){ clearInterval(this.timer) } add = () => { this.setState(state => ({ count: state.count + 1 })) } unmount = ()=>{ root.unmount(); // ReactDOM.unmountComponentAtNode(document.getElementById('root')) } show = ()=>{ alert(this.myRef.current.value); } render() { return ( <div> <h4>当前求和为:{this.state.count}</h4> <button onClick={this.add}>+</button> <button onClick={this.unmount}>注销</button><br /> <input type="text" ref={this.myRef} /> <button onClick={this.show}>提示输入内容</button> </div> ) } } //这段代码定义了一个名为countClass的React组件,它实现了以下功能: //1.导入了React库和Component类。 //2.导入了root,用于获取根组件的引用。 //3.定义了一个名为countClass的类,继承自Component类。 //4.在组件的state中定义了一个名为count的属性,初始值为0。 //5.创建了一个名为myRef的引用,用于获取组件中的DOM元素。 //6.在组件挂载时(componentDidMount)设置一个定时器,每隔1000毫秒(1秒)更新count的状态。 //7.在组件卸载时(componentWillUnmount)清除定时器。 //8.定义了一个名为add的方法,用于更新count的状态。 //9.定义了一个名为unmount的方法,用于卸载根组件(root)。 //10.定义了一个名为show的方法,用于显示输入框中的内容。 //11.在组件的render方法中,返回了一个包含计数器、加法按钮、注销按钮和输入框的元素。 -
函数组件实现代码
javascriptimport React from 'react' import { root } from '../../index'; function Demo() { /** * useState()说明: * 参数:第一次初始化指定的值在内部作缓存 * 返回值:包含2个元素的数组,第一个为内部当前状态,第二个为更新状态值的函数 */ const [count,setCount] = React.useState(0) const myRef = React.useRef() /** * React.useEffect(()=>{},[]): * 第二个参数为[],相当于componentDidMount() * 第二个参数不为[]或没有传,相当于componentDidMount()+componentDidUpdate() */ React.useEffect(()=>{ let timer = setInterval(()=>{ setCount(count => count+1) },1000) return ()=>{ // 组件卸载前执行,相当于componentWillUnmountt() clearInterval(timer) } },[]) function add() { /** * setCount()两种写法: * setCount(newValue):参数为非函数值,直接指定新的状态值,内部用其覆盖原来的状态值 * setCount(value => newValue):参数为函数,接受原本的状态,返回新的状态,内部用其覆盖原来的状态值 */ setCount(count+1) // setCount(count => count+1) } function unLoad(){ // 卸载根节点root root.unmount(); } function show(){ alert(myRef.current.value) } return ( <div> <h4>当前求和为:{count}</h4> <button onClick={add}>+</button> <button onClick={unLoad}>卸载</button><br /> <input type="text" ref={myRef} /> <button onClick={show}>提示输入内容</button> </div> ) } export default Demo
Hooks的使用
种草小幺儿.2023-11-11 16:27
相关推荐
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议前端小万1 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"三十而立洋1 天前
Cookie 详解:从产生到安全,一次讲透卡布鲁1 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘李少兄1 天前
JavaScript 隐式全局变量解析汉堡大王95271 天前
Jev:不是聊天机器人, 而是一个智能 if 语句梦想很大很大2 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践计算机魔术师2 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物