一、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
相关推荐
用户2986985301413 小时前
在 React 中使用 JavaScript 将 Excel 转换为 SVG
前端·javascript·react.js
labixiong14 小时前
手写Promise--微任务、静态方法、async/await 全搞懂(三)
前端·javascript
铁皮饭盒15 小时前
3行代码搞定页面截图,Bun.WebView真的简单
javascript
kyriewen1 天前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
山河木马1 天前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
小林攻城狮1 天前
使用 Transport 节流解决 Vercel AI SDK 流式渲染卡死问题
前端·react.js
前端缘梦1 天前
告别 TS 运行时类型漏洞!Zod 完整入门实战教程(前端 / 全栈必备)
前端·react.js·全栈
tangdou3690986551 天前
AI真好玩系列-2分钟快速了解DeepAgents | Quick Guide to DeepAgents in 2 Minutes
前端·javascript·后端
张元清1 天前
React useIntersectionObserver Hook:懒加载与可见性检测(2026)
javascript·react.js
彭于晏爱编程1 天前
纯 JS + Node,一个下午手搓了能读懂公司代码的 AI 助手,老板以为我转行了
前端·javascript