基础介绍
基本类型
type BasicTypes = {
message: string
count: number
disabled: boolean
names: string[]
id: string | number
}
联合类型
- 例如:自定义
ajax
时,一般 method
就那么具体的几种:get
、post
、put
等。 大家都知道需要传入一个 string
型,你可能会这么写:
type Method = string
type Method = 'get' | 'post' | 'put'
对象类型
type ObjectTypes = {
obj3: {
id: string
title: string
}
objArr: {
id: string
title: string
}[]
}
type ObjectTypes = {
obj: object
obj2: {}
}
- 正确的写法,推荐使用
Record
来定义对象类型
type ObjectTypes = {
obj: Record<string, unknown>
obj2: Record<string, never>
obj3: unknown
dict1: {
[key: string]: MytypeHere
}
dict2: Record<string, MytypeHere>
}
函数类型
- 函数类型不建议直接给
Function
类型,有明确的参数类型、个数与返回值类型最佳。
type FunctionTypes = {
func: Function
func2: (a: number, b: number) => number
}
可选属性
- 有时候我们定义的对象,不是所有属性都是必须的,这时候可以使用
?
来表示可选属性,例如在 react
中的 props
就是可选属性
type AppProps = {
name: string
age?: number
[propName: string]: any
}
const YourComponent = ({ name, age, ...other }: AppProps) => (
<div>
{`Hello, my name is ${name}, ${age || 'unknown'}`}
<Other {...other} />
</div>
)
React Prop 类型
React
中的 props
有很多类型,这里列举几个常用的
export declare interface AppProps {
children1: JSX.Element
children2: JSX.Element | JSX.Element[]
children3: React.ReactChildren
children4: React.ReactChild[]
children: React.ReactNode
functionChildren: (name: string) => React.ReactNode
style?: React.CSSProperties
onChange?: React.FormEventHandler<HTMLInputElement>
}
函数式组件
type AppProps = { message: string }
const App = ({ message }: AppProps) => <div>{message}</div>
type AppProps = { title: string }
const App: React.FC<AppProps> = ({ children, title }) => (
<div title={title}>{children}</div>
)
Hooks
useState
type AppProps = { message: string }
const App = () => {
const [data] = useState<AppProps | null>(null)
return <div>{data && data.message}</div>
}
useEffect
type AppProps = { message: string }
const App = ({ message }: AppProps) => {
useEffect(() => {
console.log(message)
axios.get('https://api.github.com').then((result) => {
console.log(result)
})
const fetchData = async () => {
const result = await axios.get('https://api.github.com')
console.log(result)
}
fetchData()
;(async () => {
const result = await axios.get('https://api.github.com')
console.log(result)
})()
}, [message])
return <div>{message}</div>
}
useRef
useRef
: 用于获取 DOM
节点,或者保存变量
const ref1 = useRef<HTMLElement>(null!)
const ref2 = useRef<HTMLElement | null>(null)
function MyComponent() {
const ref1 = useRef<HTMLElement>(null!)
useEffect(() => {
doSomethingWith(ref1.current)
})
return <div ref={ref1}> etc </div>
}
function TextInputWithFocusButton() {
const inputEl = React.useRef<HTMLInputElement>(null)
const onButtonClick = () => {
if (inputEl && inputEl.current) {
inputEl.current.focus()
}
inputEl.current?.focus()
}
return (
<>
<input ref={inputEl} type='text' />
<button onClick={onButtonClick}>Focus the input</button>
</>
)
}
useReducers
const initialState = { count: 0 }
type ACTIONTYPE =
| { type: 'increment'; payload: number }
| { type: 'decrement'; payload: string }
| { type: 'initial' }
function reducer(state: typeof initialState, action: ACTIONTYPE) {
switch (action.type) {
case 'increment':
return { count: state.count + action.payload }
case 'decrement':
return { count: state.count - Number(action.payload) }
case 'initial':
return { count: initialState.count }
default:
throw new Error()
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement', payload: '5' })}>
-
</button>
<button onClick={() => dispatch({ type: 'increment', payload: 5 })}>
+
</button>
</>
)
}
useContext
interface AppContextInterface {
state: typeof initialState
dispatch: React.Dispatch<ACTIONTYPE>
}
const AppCtx = React.createContext<AppContextInterface>({
state: initialState,
dispatch: (action) => action,
})
const App = (): React.ReactNode => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<AppCtx.Provider value={{ state, dispatch }}>
<Counter />
</AppCtx.Provider>
)
}
function Counter() {
const { state, dispatch } = React.useContext(AppCtx)
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'decrement', payload: '5' })}>
-
</button>
<button onClick={() => dispatch({ type: 'increment', payload: 5 })}>
+
</button>
</>
)
}
参考资料