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</>
    )
}
相关推荐
NEXT063 分钟前
受控与非受控组件
前端·javascript·react.js
NEXT0621 分钟前
防抖(Debounce)与节流(Throttle)解析
前端·javascript·面试
早點睡3901 小时前
高级进阶 React Native 鸿蒙跨平台开发:react-native-svg(CAPI) 矢量图形代码指南
react native·react.js·harmonyos
mqiqe1 小时前
pnpm 和npm 有什么区别?
前端·npm·node.js
呆子小木心2 小时前
Vue2或Vue3项目引用百度地图
javascript·vue.js·typescript·前端框架·html5
Swift社区2 小时前
React 项目生产环境构建与静态资源优化
前端·react.js·前端框架
ZaneAI2 小时前
🚀 Vercel AI SDK 使用指南: 子代理 (Subagents)
react.js·agent
A小码哥2 小时前
基于 Trae + 国产 GLM-4.7模型的任务驱动式软件开发实践
前端
上海合宙LuatOS2 小时前
LuatOS核心库API——【fft 】 快速傅里叶变换
java·前端·人工智能·单片机·嵌入式硬件·物联网·机器学习
瑶瑶领先_2 小时前
react - isValidElement 判断参数是否是一个有效的ReactElement
前端