文章目录
- 安装
- useState
- props 传参
- 数据传参,标签嵌套传参
- 函数传参
- useRef useEffect 获取dom 副作用hooks
安装
npm create vite@latest
执行后选择react ts
useState
使用ts写法 type声明数据格式
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 传参
数据传参,标签嵌套传参
import './App.css'
type Props ={className? :stringchildren?:React.ReactNode
}
function Button(props:Props) {const {className,children} =propsconsole.log(children);return (<><button className={className}>{children}</button></>)
}function App() {return (<><Button className="text"></Button><Button><span>asds</span></Button></>)
}export default App
函数传参
import './App.css'
type Props = {onGetMsg:(msg:string)=>void
}
function Button(props: Props) {const {onGetMsg} =propsreturn (<><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
定时器设置
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