React Typescript 速查表
以下是我在使用 React + Typescript 构建项目时发现的一些有用的模式。刚开始的时候,我发现 JSX 和 React 类型并不明显,也没有特别完善的文档,所以我想维护一个列表,列出在不同情况下应该使用的类型。
这只是一个开始,所以我很想知道你们觉得哪些模式有用,以及我应该把哪些模式添加到列表中。另外,如果这里有什么我不应该做的,我也很乐意知道!
目录
孩子们
interface Props {
children?: React.ReactNode
}
活动
interface Props {
// Use the specific HTML element targeted
onClick?: (event: MouseEvent<HTMLButtonElement>) => void
}
转发 Prop
将命名的 props 对象转发给元素:
interface Props {
buttonProps?: JSX.IntrinsicElements['button']
}
const Container = ({ buttonProps }: Props) => (
<div>
<button {...buttonProps}></button>
</div>
)
将顶级属性转发给元素:
interface Props extends JSX.IntrinsicElements['button'] {}
const ExtendedButton = (props: Props) => (
<button {...props} />
)
样式
// utils.d.ts
declare interface StyleProps {
style?: React.CSSProperties
className?: string
}
// Button.tsx
interface ButtonProps extends StyleProps {
label: string
}
const Button = ({ label, ...styleProps }: ButtonProps) => (
<button {...styleProps}>{label}</button>
)
参考文献
元素引用:
const liRef = useRef<HTMLLIElement>(null)
其他参考也是可能的:
const valueRef = useRef<number>(0)