React组件中书写typescript类型
安装依赖包:
npm install @types/react @types/react-dom
JSX.Element
组件类型JSX.Element
,也可以使用React.ReactElement
:
function App() :JSX.Element{
return (
<div>
</div>
);
}
export default App;
ReactNode
ReactNode
的源码里写着会包含多种类型
关系:ReactNode>ReactElement>JSX.Element
type ReactNode =
| ReactElement
| string
| number
| bigint
| Iterable<ReactNode>
| ReactPortal
| boolean
| null
| undefined
| DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES[
keyof DO_NOT_USE_OR_YOU_WILL_BE_FIRED_EXPERIMENTAL_REACT_NODES
]
| Promise<AwaitedReactNode>;
FunctionComponent
FC
和FunctionComponent
是一样的,参数都是props
,返回值是ReactNode
const cxk:React.FunctionComponent<number> = ()=>{
return <div>123</div>
}
Hook类型
useState
的类型:
const [count, setCount] = useState<number>(0);
useRef
的类型:
保存dom
引用的时候,参数传一个null
const countRef = useRef<HTMLDivElement>(null);
PropsWithChildren
特别适用于组件的 props
,当组件需要接收 children
时
type PropsWithChildren<P = unknown> = P & { children?: ReactNode | undefined };
例如:
import React, { PropsWithChildren } from 'react';
type ButtonProps = {
label: string;
};
const Button: React.FC<PropsWithChildren<ButtonProps>> = ({ label, children }) => {
return (
<button>
{label}
{children}
</button>
);
}
export default Button;
CSSProperties
CSSProperties 可以精确地为 React 组件的 style 属性定义类型。 CSSProperties 包含了所有合法的 CSS 属性,并且会自动将 CSS 属性从短横线(例如 background-color)转换为驼峰命名 例如:
// 使用 CSSProperties 类型
const divStyle: React.CSSProperties = {
backgroundColor: 'lightblue',
width: '100px',
height: '100px',
borderRadius: '10px',
fontSize: '20px',
};
HTMLAttributes
React 中使用 HTML 元素时,传递给这些元素的属性是有效的 HTML 属性,并提供类型推导和类型检查。
例如:
const MyComponent: React.FC<React.HTMLAttributes<HTMLDivElement>> = (props) => {
return <div {...props}>Hello World!</div>;
};
ComponentProps
类型参数传入标签名,效果和 HTMLAttributes 一样