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</>
    )
}
相关推荐
Mintopia10 分钟前
🚀 Next.js 全栈 Web Vitals 监测与 Lighthouse 分析
前端·javascript·全栈
ITKEY_12 分钟前
flutter日期选择国际化支持
开发语言·javascript·flutter
Mintopia12 分钟前
🤖 AIGC + CMS:内容管理系统智能化的核心技术支撑
前端·javascript·aigc
HelloGitHub15 分钟前
这款开源调研系统越来越“懂事”了
前端·开源·github
whysqwhw18 分钟前
hippy的主要原理
前端
子兮曰21 分钟前
🚀95%的前端开发者都踩过坑:JavaScript循环全解析,从基础到高阶异步迭代
前端·javascript·性能优化
2401_8534068821 分钟前
Tdesign-React 组件 Card 实现头部固定,内容区单独可滚动
前端·react.js·tdesign
蓝倾97624 分钟前
小红书获取用户作品列表API接口操作指南
java·服务器·前端·python·电商开放平台·开放api接口
小桥风满袖24 分钟前
极简三分钟ES6 - 数值的扩展
前端·javascript
北辰alk25 分钟前
React 组件间数据共享全方位指南:从 Props 到状态管理
前端