props作为React组件的参数入口,添加了类型之后可以限制参数输入以及在使用props有良好的类型提示
interface Props {
className: string
}
export const Button = (props:Props)=>{
const { className } = props
return <button className={ className }>Test</button>
}
type Props = {
className: string
}
export const Button = (props:Props)=>{
const { className } = props
return <button className={ className }>Test</button>
}
children属性和props中其他的属性不同,它是React系统中内置的,其它属性我们可以自由控制其类型,children属性的类型最好由React内置的类型提供,兼容多种类型
type Props = {
children: React.ReactNode
}
export const Button = (props: Props)=>{
const { children } = props
return <button>{ children }</button>
}
// props + ts
type Props = {
onGetMsg?: (msg: string) => void
}
function Son(props: Props) {
const { onGetMsg } = props
const clickHandler = () => {
onGetMsg?.('this is msg')
}
return <button onClick={clickHandler}>sendMsg</button>
}
function App() {
const getMsgHandler = (msg: string) => {
console.log(msg)
}
return (
<>
<Son onGetMsg={(msg) => console.log(msg)} />
<Son onGetMsg={getMsgHandler} />
</>
)
}
export default App
为事件回调添加类型约束需要使用React内置的泛型函数来做,比如最常见的鼠标点击事件和表单输入事件:
function App(){
const changeHandler: React.ChangeEventHandler<HTMLInputElement> = (e)=>{
console.log(e.target.value)
}
const clickHandler: React.MouseEventHandler<HTMLButtonElement> = (e)=>{
console.log(e.target)
}
return (
<>
<input type="text" onChange={ changeHandler }/>
<button onClick={ clickHandler }> click me!</button>
</>
)
}