TypeScript检查本质上就是:在技术上可以帮你检查的地方帮你检查,不能检查的地方要求你明确声明。
说明:假定我们在 tsconfig.js 中设置了 strict: false。
使用props.children
想要在 .ts文件中新增如下代码是会告警的:
因此我们需要给props进行类型声明,可以提供 React 提供的函数组件类型:
// type React.FC<P = {}> = React.FunctionComponent<P>const AppBody: React.FC = (props) => {return (<div className="app-body">{props.children}</div>);}
React.FC代表函数组件的类型,我们没有给FC定义范型但直接拿到了children,原因是:
Notice that children isn’t defined in Props. Instead, it is already defined in the FC type.
详细的定义可以参考官方的声明文件:
type FC<P = {}> = FunctionComponent<P>;interface FunctionComponent<P = {}> {(props: PropsWithChildren<P>, context?: any): ReactElement<any, any> | null;propTypes?: WeakValidationMap<P>;contextTypes?: ValidationMap<any>;defaultProps?: Partial<P>;displayName?: string;}type PropsWithChildren<P> = P & { children?: ReactNode };
更多在Reac组件中获取children的做法可以参考这篇文章。
混合自定义参数使用
假设父组件中想传入一个title和一个fn:
<AppBody title={'passed in title'} fn={() => { return "fn exectued" }}>body content</AppBody>
有多种方式可以定义被引用的组件:
// 方式1interface Props {title: string,fn?: () => string}const AppBody: React.FC | Props = (props) => {return (<div className="app-body">{props.children}</div>);}// 方式2interface Props {children: React.ReactNode,title: string,fn?: () => string}const AppBody = (props: Props) => {return (<div className="app-body">{props.children}</div>);}export default AppBody;
