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</>
    )
}
相关推荐
魔术师卡颂3 分钟前
提问量暴跌 80% ,Stack Overflow 却赚翻了?
前端·后端·ai编程
rocky1914 分钟前
什么,你还没用 claude,out 了吧!
前端·程序员
冰暮流星10 分钟前
javascript如何转换为字符串与布尔型
java·开发语言·javascript
2501_9481226319 分钟前
React Native for OpenHarmony 实战:Steam 资讯 App 个人中心页面
javascript·react native·react.js·游戏·ecmascript·harmonyos
Younglina20 分钟前
想提升专注力?我做了一个web端的训练工具
前端·vue.js·游戏
NEXT0637 分钟前
CSS 选择器深度实战:从“个十百千”权重法到零 DOM 动画的降维打击
前端·css
Mapmost42 分钟前
防患未“燃”:掌握森林火灾仿真分析,精准把控火势蔓延趋势
前端
半世轮回半世寻1 小时前
前端开发里最常用的5种本地存储
前端·javascript
OpenTiny社区1 小时前
TinyPro v1.4.0 正式发布:支持 Spring Boot、移动端适配、新增卡片列表和高级表单页面
java·前端·spring boot·后端·开源·opentiny
爱上妖精的尾巴1 小时前
7-9 WPS JS宏 对象使用实例6:按条件读取多表再拆成多表
前端·javascript·wps·jsa