当前位置: 首页 > news >正文

React Hooks UseRef的用法

         开发环境时Taro+React Native+TypeScript

export interface TimerRef{timeShow: ()=>{};getCurrentTime: () => number;
}// 修改这里:添加 props 参数,即使不使用也要保留位置
const Timer = forwardRef<TimerRef, {}>((props, ref) => {const [count, setCount] = useState(0);const timerRef = useRef<NodeJS.Timeout | null>(null);const memoryName = 'Time Pace'// 暴露方法给父组件useImperativeHandle(ref, ()=>({timeShow: ()=>{console.log("定时器的当前时间: current time = ", count)console.log("memoryName = ", memoryName)},getCurrentTime: ()=>{return count}}))const startTimer = () => {// 如果已经有定时器在运行,先清除if (timerRef.current !== null) {clearInterval(timerRef.current);}timerRef.current = setInterval(() => {setCount(prev => prev + 1);}, 1000);};const stopTimer = () => {if (timerRef.current !== null) {clearInterval(timerRef.current);timerRef.current = null; // 清除后重置为 null}};useEffect(() => {return () => {if (timerRef.current !== null) {clearInterval(timerRef.current);}};}, []);return (<div><p>计数: {count}</p><button className='btn' style={{marginRight: 20}} onClick={startTimer}>开始</button><button className='btn' onClick={stopTimer}>停止</button></div>);
})
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react'
import { View, Text, Button } from '@tarojs/components'
import './index.scss'interface IProps{color: string;size: string;originalPrice?: string;description?: string;likeStar?: string;price: number;
}const DressPaper = (props:IProps) => {const [price, setPrice] = useState(props.price)const [likeStar, setLikeStar] = useState(props.likeStar || 'star, ')const priceRef = useRef<HTMLSpanElement>(null)const preStarsNumRef = useRef(0)const timeRef = useRef<TimerRef>(null)// 改变价格const changeDressPrice = ()=>{setPrice(prePrice =>{return ++prePrice });// 使用useRef动态改变元素的样式if(priceRef.current){// const element = priceRef.current as unknown as HTMLElement;priceRef.current.style.color = 'blue'}}// 使用ref存储上一次的值// 增加like Star并记录上一次增加后的次数const addLikeStar = ()=>{setLikeStar(preLikeStar => {return preLikeStar + 'star, '})// useRef修饰的值跨越整个生命周期都不会改变,但当值改变时也可以更新在页面中preStarsNumRef.current++}//子组件的事件处理const handleSubShow = ()=>{console.log("通过ref在子组件中获取的当前时间 current time = ", timeRef.current?.getCurrentTime())timeRef.current?.timeShow()}return (<View><View className='container'><Text ref={priceRef} className='txt'>Price: {'$' + price}</Text><Text className='txt'>{likeStar}</Text><Text className='txt'>上一次增加的star个数为:{preStarsNumRef.current}</Text></View><View><Button className='btn' onClick={changeDressPrice}>change price</Button><Button className='btn' onClick={addLikeStar}>add like star</Button></View><View style={{backgroundColor: '#cc9999'}}><Text className='txt'>使用useRef做父子组件间的通信,存储定时器, 组件销毁时清除定时器</Text><Timer ref={timeRef}></Timer><Button className='btn' onClick={handleSubShow}>父组件调用子组件方法,修改子组件的属性</Button></View></View>);
}export default DressPaper;
import UseRefComponent from "../Hooks/UseRef";
<UseRefComponent color='blue' size='m' price={20}></UseRefComponent>

下面的是样式scss文件

.container {display: flex;flex-direction: column;padding: 20px;background-color: #ADD8E6;margin-bottom: 40px;
}.txt {height: 44px;padding: 15px 100px;margin-bottom: 7px;background-color: #FFE4E1;font-size: 26px;
}.btn {height: 64px;// padding: 15px 100px 15px 100px;margin-bottom: 7px;background-color: #D8BFD8;font-size: 28px;
}.buttonContainer {display: flex;flex-direction: row;justify-content: space-around;margin-bottom: 20px;
}.input {background-color: white;padding: 10px;border: 1px solid #ccc;border-radius: 5px;
}

http://www.dtcms.com/a/346846.html

相关文章:

  • 【Win10 画图板文字方向和繁体问题】
  • 浮点数比较的致命陷阱与正确解法(精度问题)
  • linux下的网络编程:基础概念+UDP编程
  • Class41样式迁移
  • 55.Redis搭建主从架构
  • 计算机网络 各版本TLS握手的详细过程
  • CSS学习步骤及详解
  • 美食菜谱数据集(13943条)收集 | 智能体知识库 | AI大模型训练
  • JUC之虚拟线程
  • ArcGIS Pro 安装路径避坑指南:从崩溃根源到规范实操(附问题修复方案)
  • 运行npm run命令报错“error:0308010C:digital envelope routines::unsupported”
  • 使用 AD 帐户从 ASP.NET 8 容器登录 SQL Server 的 Kerberos Sidecar
  • 【深入理解 Linux 网络】收包原理与内核实现(下)应用层读取与 epoll 实现
  • 5G物联网的现实与未来:CTO视角下的成本、风险与破局点
  • 嵌入式学习日记(33)TCP
  • OpenFeign相关记录
  • 【嵌入式】【搜集】RTOS相关技术信息整理
  • Ubuntu2204server系统安装postgresql14并配置密码远程连接
  • 【python与生活】如何自动总结视频并输出一段总结视频?
  • FastAPI + SQLAlchemy 数据库对象转字典
  • 【力扣 Hot100】每日一题
  • C++之list类的代码及其逻辑详解 (中)
  • Java线程的几种状态 以及synchronized和Lock造成的线程状态差异,一篇让你搞明白
  • Linux服务器Systemctl命令详细使用指南
  • GitLab CI:安全扫描双雄 SAST vs. Dependency Scanning 该如何抉择?
  • 智慧园区人车混行误检率↓78%!陌讯动态决策算法实战解析
  • html链接的target属性
  • Win11 下卸载 Oracle11g
  • 《文字的本体论突围:从工具论到符号学革命的范式转换》
  • B.30.01.1-Java并发编程及电商场景应用