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</>
    )
}
相关推荐
bin91535 分钟前
DeepSeek 助力 Vue 开发:打造丝滑的复制到剪贴板(Copy to Clipboard)
前端·javascript·vue.js·ecmascript·deepseek
晴空万里藏片云2 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一2 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球2 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7232 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
无责任此方_修行中3 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
Σίσυφος19004 小时前
halcon 条形码、二维码识别、opencv识别
前端·数据库
学代码的小前端4 小时前
0基础学前端-----CSS DAY13
前端·css
dorabighead5 小时前
JavaScript 高级程序设计 读书笔记(第三章)
开发语言·javascript·ecmascript
css趣多多5 小时前
案例自定义tabBar
前端