react 结合 ts

useState 中使用 ts

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

type Props = {
    className: string
    children: React.ReactNode
}
function Button(props: Props) {
    const {className, children} = props
    return <button className={className}>{children}</button>
}
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

function App() {
    const domRef = useRef<HTMLInputElement>(null)
    useEffect(() => {
        console.log(domRef.current?.value)
    }, []);
    return (
        <>
            <input ref={domRef}/>
        </>
    )
}
export default App
function App() {
    const timerRef = useRef<number | undefined>(undefined)
    useEffect(() => {
        timerRef.current = setInterval(() => {
            console.log('1')
        }, 1000)
        return ()=> clearInterval(timerRef.current)
    }, []);
    return (
        <>this is div</>
    )
}

相关推荐

  1. react 结合 ts

    2024-06-05 19:40:14       8 阅读
  2. <span style='color:red;'>react</span>+<span style='color:red;'>ts</span>

    react+ts

    2024-06-05 19:40:14      29 阅读
  3. TS-React:useRef 使用

    2024-06-05 19:40:14       31 阅读
  4. 创建React+Ts项目

    2024-06-05 19:40:14       16 阅读
  5. React 中使用 TS

    2024-06-05 19:40:14       14 阅读
  6. 配置Vite+React+TS项目

    2024-06-05 19:40:14       26 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-05 19:40:14       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-05 19:40:14       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-05 19:40:14       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-05 19:40:14       20 阅读

热门阅读

  1. WebSocket 断网重连、心跳检测功能封装

    2024-06-05 19:40:14       8 阅读
  2. xjoi题库一级八段题解(c语言版)

    2024-06-05 19:40:14       8 阅读
  3. 数据库到服务器提权

    2024-06-05 19:40:14       7 阅读
  4. 【C language】两个数的交换

    2024-06-05 19:40:14       6 阅读
  5. ML307R OpenCPU UDP使用

    2024-06-05 19:40:14       8 阅读
  6. 华为欧拉 EulerOS V2.0 SP5 一键安装 Oracle 19C 单机

    2024-06-05 19:40:14       10 阅读
  7. 代码随想录算法训练营第20天|二叉树

    2024-06-05 19:40:14       8 阅读
  8. ORACLE 查询SQL优化

    2024-06-05 19:40:14       9 阅读
  9. 在Spring Boot中集成H2数据库:完整指南

    2024-06-05 19:40:14       9 阅读