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</>
    )
}
相关推荐
0思必得0几秒前
[Web自动化] CSS布局与定位
前端·css·自动化·html·web自动化
朱 欢 庆1 分钟前
在docker容器里 使用Jenkins部署前端项目
前端·经验分享·docker·jenkins
开发者小天2 分钟前
react中recharts使用的示例
前端·javascript·react.js
悟能不能悟6 分钟前
如何部署wiki.js
开发语言·javascript·ecmascript
网络风云6 分钟前
AJAX与Fetch--异步Web请求的深度对比
前端·ajax·okhttp
LYFlied8 分钟前
【每日算法】LeetCode 763. 划分字母区间(贪心算法)
前端·算法·leetcode·面试·贪心算法
幺零九零零8 分钟前
全栈程序员-前端第一节-npm 是什么?
前端·npm·node.js
Rysxt_11 分钟前
UniApp pages.json 配置完全指南
开发语言·前端·javascript
BD_Marathon14 分钟前
Vue3_组件传参问题
前端·javascript·vue.js
Coffeeee15 分钟前
Android15适配之edge-to-edge和16kb到底咋适配
android·前端·android studio