react 结合 ts

useState 中使用 ts

tsx 复制代码
type User = {
    name: string
    age: number
}
function App() {
    // 直接使用对象
    // const [user, setUser] = useState<User | null>(null)
    // const [user, setUser] = useState<User>({
    //     name: 'jack',
    //     age: 18
    // })
    // 使用函数返回对象
    const [user, setUser] = useState<User>(()=> {
        return {
            name: 'jack',
            age: 18
        }
    })
    // setUser 也同理有 直接修改 和 使用函数返回对象 的修改形式
    return (
        <>this is an app</>
    )
}
export default App

props 中使用 ts

tsx 复制代码
type Props = {
    className: string
    children: React.ReactNode
}
function Button(props: Props) {
    const {className, children} = props
    return <button className={className}>{children}</button>
}
tsx 复制代码
type Props = {
    onGetMsg?: (msg: string) => void
}
function Button(props: Props) {
    const {onGetMsg} = props
    const clickHandler = () => {
        onGetMsg?.('hello')
    }
    return <button onClick={clickHandler}>sendMsg</button>
}
function App() {
    return (
        <>
            {/*内联函数会自动进行类型推导,如果是外部函数 还需要手动进行类型约束*/}
            <Button onGetMsg={(msg) => console.log(msg)}/>
        </>
    )
}
export default App

useRef 使用 ts

tsx 复制代码
function App() {
    const domRef = useRef<HTMLInputElement>(null)
    useEffect(() => {
        console.log(domRef.current?.value)
    }, []);
    return (
        <>
            <input ref={domRef}/>
        </>
    )
}
export default App
tsx 复制代码
function App() {
    const timerRef = useRef<number | undefined>(undefined)
    useEffect(() => {
        timerRef.current = setInterval(() => {
            console.log('1')
        }, 1000)
        return ()=> clearInterval(timerRef.current)
    }, []);
    return (
        <>this is div</>
    )
}
相关推荐
欣然~4 分钟前
FachuanHybridSystem 项目 Windows 完整安装启动文档
前端
anyup6 分钟前
uView Pro 的主题系统有多强大?3 分钟设计 uni-app 企业级 UI 主题
前端·vue.js·uni-app
BUG_Jia8 分钟前
Vue 3 组件封装与使用:保姆级教程
前端·javascript·vue.js
奇舞精选12 分钟前
观察 AIRI 源码:一个 Agent 系统如何处理入口、扩展与执行闭环
前端·openai
思成Codes14 分钟前
从本质看:Vue3 为什么运用 LIS 算法
javascript·vue.js
江湖行骗老中医24 分钟前
Pinia 是 Vue 的专属状态管理库
前端·javascript·vue.js
用户693717500138425 分钟前
Android 开发,别只钻技术一亩三分地,也该学点“广度”了
android·前端·后端
郑鱼咚26 分钟前
别再神化Spec了,它可能只是AI Coding的临时补丁
前端
张元清30 分钟前
React 鼠标追踪与交互效果实战
前端·javascript·面试
MinterFusion31 分钟前
HTML DOM元素的定位问题
前端·css·html