Hooks的使用

编程入门 行业动态 更新时间:2024-10-10 10:31:25

<a href=https://www.elefans.com/category/jswz/34/1768095.html style=Hooks的使用"/>

Hooks的使用

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

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

    案例:

  • 类组件实现代码

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

    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(){// 卸载根节点rootroot.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-15 17:51:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603714.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Hooks

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!