一、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
相关推荐
kyriewen2 小时前
写组件文档写到吐?我用AI自动生成Storybook,同事以后直接抄
前端·javascript·面试
五点六六六2 小时前
你敢信这是非Native页面写出来的渐变效果吗🌝(底层原理解析
前端·javascript·面试
吃西瓜的年年3 小时前
TypeScript
javascript·ubuntu·typescript
熊猫_豆豆6 小时前
一个模拟四轴飞行器在随机气流扰动下悬停飞行的交互式3D仿真网页,包含飞行器建模与PID控制算法
javascript·3d·html·四轴无人机模拟飞行
来恩10037 小时前
jQuery选择器
前端·javascript·jquery
前端繁华如梦7 小时前
树上挂苹果还是挂玻璃球?Three.js 程序化果实的完整实现指南
前端·javascript
CDwenhuohuo8 小时前
优惠券组件直接用 uview plus
前端·javascript·vue.js
川冰ICE8 小时前
TypeScript装饰器与元编程实战
前端·javascript·typescript
AI砖家8 小时前
Vue3组件传参大全,各种传参方式的对比
前端·javascript·vue.js
希望永不加班8 小时前
var局部变量类型推断的利弊
java·服务器·前端·javascript·html