Hooks的使用

  • 作用:在函数组件中使用state以及其他的React特性

  • 常用的hook:React.useState()、React.useEffect()、React.useRef()

    案例:

  • 类组件实现代码

    javascript 复制代码
    import 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方法中,返回了一个包含计数器、加法按钮、注销按钮和输入框的元素。
  • 函数组件实现代码

    javascript 复制代码
    import 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
相关推荐
J不A秃V头A40 分钟前
Vue3:编写一个插件(进阶)
前端·vue.js
光影少年1 小时前
usemeno和usecallback区别及使用场景
react.js
司篂篂1 小时前
axios二次封装
前端·javascript·vue.js
姚*鸿的博客2 小时前
pinia在vue3中的使用
前端·javascript·vue.js
宇文仲竹2 小时前
edge 插件 iframe 读取
前端·edge
Kika写代码2 小时前
【基于轻量型架构的WEB开发】【章节作业】
前端·oracle·架构
天下无贼!3 小时前
2024年最新版Vue3学习笔记
前端·vue.js·笔记·学习·vue
Jiaberrr3 小时前
JS实现树形结构数据中特定节点及其子节点显示属性设置的技巧(可用于树形节点过滤筛选)
前端·javascript·tree·树形·过滤筛选
赵啸林3 小时前
npm发布插件超级简单版
前端·npm·node.js
我码玄黄4 小时前
THREE.js:网页上的3D世界构建者
开发语言·javascript·3d