react hook 函数组件

75 阅读1分钟

基础写法

import React, { FC, ReactElement, useRef } from 'react'
interface IProps {
    // 组件参数
}
const Input: FC<IProps> => ({
    // IProps参数导入
}): ReactElement => {
    const inputRef = useRef<HTMLInputElement>(null)
    // 断言的方式取得input的value
    
    // 弹窗展示input的value
    const getValue = (): void => {
        // const val: string = inputRef.current.value.trim()
        // inputRef.current会出现波浪线提示,因为inputRef.current可能是个null,加上!表示inputRef.current是一定存在的
        const val: string = inputRef.current!.value.trim()
        alert(val)
    }
    return (
        <div>
            <input ref={inputRef} />
            <button onClick={getValue}>获取input输入框的值</button>
        </div>
    )
}