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</>
    )
}
相关推荐
写不来代码的草莓熊39 分钟前
vue前端面试题——记录一次面试当中遇到的题(9)
前端·javascript·vue.js
JinSo1 小时前
pnpm monorepo 联调:告别 --global 参数
前端·github·代码规范
程序员码歌1 小时前
豆包Seedream4.0深度体验:p图美化与文生图创作
android·前端·后端
urhero1 小时前
工作事项管理小工具——HTML版
前端·html·实用工具·工作事项跟踪·任务跟踪小工具·本地小程序
二十雨辰1 小时前
eduAi-智能体创意平台
前端·vue.js
golang学习记1 小时前
从0死磕全栈之Next.js connection() 函数详解:强制动态渲染的正确姿势(附实战案例)
前端
郝学胜-神的一滴1 小时前
Three.js光照技术详解:为3D场景注入灵魂
开发语言·前端·javascript·3d·web3·webgl
m0dw1 小时前
vue懒加载
前端·javascript·vue.js·typescript
国家不保护废物2 小时前
手写 Vue Router,揭秘路由背后的魔法!🔮
前端·vue.js
菜鸟‍2 小时前
【前端学习】仿Deepseek官网AI聊天网站React
前端·学习·react.js