函数组件 FC
FC 的两种写法
- 用FC泛型约束props
- 直接给props指定类型
// 第一种写法
import {FC} from 'react';
interface IProps{
name:string;
age:number;
sex?:1|2;
}
const FunctionComponent:FC<IProps>= ({name,age,sex=1})=>(
<div>
<p>姓名:{name}</p>
<p>年龄:{age}</p>
<p>性别:{sex===1?'男':'女'}</p>
</div>
)
// 第二种写法 props 也可以直接结构 {name,age,sex=1}:Iprops
type TitleProps = {
name:string
}
const Title = (props:TitleProps)=> (<div>{props.name}</div>);
结构更具可读性
const Title = ({name}:TitleProps)=>( <div>{name}</div> );
组件的children
FC 定义组件react18以前会默认带有children
interface Iprops{
name:string;
}
const Card:FC<Iprops> = ({name}) =>{
return (
<div>
<div>{name}</p>
<div>{children}</div>
</div>
)
}
显示的定义children
interface Iprosp {
name:string;
children:React.ReactNode;
}
const Card = ({name,children}:Iprosp) =>{
return <div>
<p>{name}</p>
<p>{children}</p>
</div>
}
当我们显示的设计children时,可以确保我们永远没有children
type IProps = {
children: never
}
useState
useState 的泛型指定了返回值类型
const [name,setName] = useState<string>('lili');
const [current,setCurrent] = useState<number>(0);
const [child,setChild] = useState<{name:string;age:number;sex:1|2}>({name:'lili',age:18,sex:1});
useMemo 与 useCallback
useMemo 的泛型指定了返回值类型,useCallback 的泛型指定了参数类型
// 指定返回值的类型,不一致会报错
const name = useMemo<string>(() => 'lili' ,[]);
// 指定的是参数类型
const handler = useCallback<React.ChangeEventHandler<HTMLInputElement>>((e)=>{
console.log(e.target.value);
},[])
将属性传播到HTML元素
当我们写一个Button组件时,它可能需要所有的原生button的所有属性,我们可以用JSX.IntrinsicElements来获取button的属性
type ButtonProps = JSX.IntrinsicElements['button'];
const Button = ({...allProps}:ButtonProps)=>{
return <button {...allProps} >提交</button>
}
当我们给组件定义className及style时
type StyleButtonProps = Omit<
JSX.IntrinsicElements['button'],
'className'|'style'|'type'>&
{type:'primary'|'link'};
const StyleButton = ({type,style,...allProps}:ButtonProps)=>{
return <button
className={`btn-${type}`}
style={style}
{...allProps}
/>
}
写一个传进来什么类型就返回什么类型的自定义函数
const useDate = <T>(params: T): T => {
return params;
};
const name = useDate('lili'); // name ---> lili类型
const age = useDate<number>('lili'); // 提示number 与 string 不兼容;