一、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
相关推荐
盗德1 天前
最全音频处理WaveSurfer.js配置文档
前端·javascript
Heo1 天前
关于Gulp,你学这些就够了
前端·javascript·面试
祈澈菇凉1 天前
Next.js 零基础开发博客后台管理系统教程(八):提升用户体验 - 表单状态、加载与基础验证
前端·javascript·ux
有意义1 天前
从日常使用到代码实现:B 站签名编辑的 OOP 封装思路与实践
javascript·代码规范·ecmascript 6
nvd111 天前
SSE 流式输出与 Markdown 渲染实现详解
javascript·python
哆啦A梦15881 天前
62 对接支付宝沙箱
前端·javascript·vue.js·node.js
Tzarevich1 天前
用 OOP 思维打造可复用的就地编辑组件:EditInPlace 实战解析
javascript·前端框架
用户8168694747251 天前
Lane 优先级模型与时间切片调度
前端·react.js
豆苗学前端1 天前
面试复盘:谈谈你对 原型、原型链、构造函数、实例、继承的理解
前端·javascript·面试