-
作用:在函数组件中使用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
相关推荐
GDAL20 分钟前
HTML 中的 Canvas 样式设置全解m0_5287238125 分钟前
HTML中,title和h1标签的区别是什么?Dark_programmer26 分钟前
html - - - - - modal弹窗出现时,页面怎么能限制滚动GDAL31 分钟前
HTML Canvas clip 深入全面讲解禾苗种树32 分钟前
在 Vue 3 中使用 ECharts 制作多 Y 轴折线图时,若希望 **Y 轴颜色自动匹配折线颜色**且无需手动干预,可以通过以下步骤实现:GISer_Jing37 分钟前
Javascript排序算法(冒泡排序、快速排序、选择排序、堆排序、插入排序、希尔排序)详解贵州数擎科技有限公司1 小时前
使用 Three.js 实现流光特效JustHappy1 小时前
「我们一起做组件库🌻」做个面包屑🥖,Vue的依赖注入实战💉(VersakitUI开发实录)拉不动的猪1 小时前
刷刷题16kiramario1 小时前
【结束】JS如何不通过input的onInputFileChange使用本地mp4文件并播放,nextjs下放入public文件的视频用video标签无法打开