当前位置: 首页 > 工具软件 > react-tetris > 使用案例 >

TypeScript + React

龙涵蓄
2023-12-01
// type script definition
type GreetProps = {
	name:string
	messageCount: number
	isLoggedin:boolean
	name:{
		first:string
		last:string
	}
}
// array props
type PersonList = {
	name:{
		first:string,
		last:string
	}[]
}

// type designated
type StatusProps = {
	status:'loading'| 'success'|'error'
}

	
// react component 
type OscarProps = {
	children: React.ReactNode
}

// optionaol type
type GreetProps = {
	name:string
	messageCount?: number
}
// then in the function, use {messageCount = 0} to set the default value to zero
const {messageCount = 0} = props


// clilck envent
type ButtonProps = {
	handleClick: () => void
}
export const Button = (props: ButtonProps) => {
	return <button onClick={props.handleClick}>click<button/>
}
// then
<Button handleClick={()=> {console.log('click')}} />



// clilck envent with parameter
type ButtonProps = {
	handleClick: (event: React.MouseEvent<HTMLButtonElement>, id: number) => void
}
export const Button = (props: ButtonProps) => {
	return <button onClick={(event)=> props.handleClick(event, 1)}>click<button/>
}
-- then
<Button handleClick={(event, id)=> {console.log('click', event)}} />


// type
type InputProps = {
	value:string
	handleChange:(event: React.ChangeEvent<HTMLInputElement>) => void
}
// could be destructured by ({value, handleChange}: InputProps)
export const Input = (props: InputProps) => {
	return <input type='text' value={props.value} onChange={props.handleChange}>
}


// styles props
type ContainerProps = {
	styles: React.CSSProperties
}

export const Container = (props: ContainerProps) =>{
	return (
		<div styles={props.styles}>
			Hello
		</div>
	)
}

// type 可以export出来

// useState
type AuthUser = {
	name:string
	age:number
}
const [user, setUser] = useState<AuthUser | null>(null);
// because it is optional 
<div> Username is {user?.name}</div>
// 如果不想要null的话,可以
const [user, setUser] = useState<AuthUser>({} as AuthUser)
 类似资料: