一、Vite React+ts基础写法

文章目录


安装

npm create vite@latest

执行后选择react ts

useState

使用ts写法 type声明数据格式

ts 复制代码
import { useState } from 'react'
import './App.css'
type User = {
  a: string
}
function App() {
  const [count, setCount] = useState<User | null>(null)
  const b = () => {
    setCount(null)
    setCount({ a: "asd" })
  }
  return (
    <>
      {/* count?.a 排除ts null报错,显示页面 */}
      <button onClick={b}>{count?.a}</button>
    </>
  )
}

export default App

props 传参

数据传参,标签嵌套传参

ts 复制代码
import './App.css'
type Props ={
  className? :string
  children?:React.ReactNode
}
function Button(props:Props) {
  const {className,children} =props
  console.log(children);
  
  return (
  <>
    <button className={className}>{children}</button>
  </>
  )
}

function App() {
  return (
    <>
    <Button className="text"></Button>
    <Button>
      <span>asds</span>
    </Button>
    </>
  )
}

export default App

函数传参

ts 复制代码
import './App.css'
type Props = {
  onGetMsg:(msg:string)=>void
}
function Button(props: Props) {
  const {onGetMsg} =props
  return (
    <>
      <button onClick={()=>{onGetMsg('ASD')}}>BTUU</button>
    </>
  )
}

function App() {
  const getMsgHandler = (msg:string)=>{
    console.log(msg);
    
  }
  return (
    <>
      <Button onGetMsg={getMsgHandler}></Button>
      
    </>
  )
}

export default App

useRef useEffect 获取dom 副作用hooks

获取DOM

定时器设置

ts 复制代码
import { useEffect, useRef } from 'react'
import './App.css'

function App() {
  // 获取dom元素
  const a = useRef<HTMLInputElement>(null)
  //  useRef配合定时 延迟器使用,离开关闭
  const b = useRef<number | undefined>(undefined)
  useEffect(() => {
    //  聚焦
    a.current?.focus()
    b.current = setInterval(() => {
      console.log('123');
    }, 2000)
    return () => clearInterval(b.current)
  }, [])
  return (
    <>
      <input type="text" ref={a} />
    </>
  )
}

export default App
相关推荐
李明卫杭州3 小时前
React 复合事件系统对比解析
前端·javascript·react.js
Brilliantwxx3 小时前
【STM32】 I2C_EEPROM_test 工程(实战篇)
开发语言·stm32·单片机·嵌入式硬件·ecmascript
LEE4 小时前
前端转型全栈 01:数据建模,前端最大的盲区
前端·javascript·后端
雪芽蓝域zzs4 小时前
第四十七节:驾驶舱大屏 ECharts 图表集成
前端·javascript·vue.js
梦醒沉醉5 小时前
7、表达日期和时间(前朝遗老Date)
javascript
白雾茫茫丶5 小时前
Vibecoding 一个主题切换动画库:13 种揭幕方式
前端·vue.js·react.js
雪芽蓝域zzs6 小时前
第四十九节:TagsView 右键菜单(带三角箭头)给每个 tag 增加**鼠标右键菜单**(右键标签弹出:关闭、关闭其他、关闭全部)
前端·javascript·vue.js
এ慕ོ冬℘゜6 小时前
从零开发移动端医院挂号页面:适配、交互与前端实现详解
前端·javascript
宁渡AI大模型6 小时前
AI 全栈面试新趋势:Vibe Coding、前端、Java 后端高频面试题深度解析|河南宁渡科技有限公司编程教程
java·javascript·人工智能·python·ai大模型
东风微鸣6 小时前
AI依赖更新别裸奔🚨
javascript