跳至主要内容

[TS] React Snippets of TypeScript

Create React App

$ npx create-react-app typescript-react-sandbox --template typescript

Functional Component

JSX

使用 interface 定義 Props:

interface FooProps {
bar: string;
children: React.ReactNode;
}

const Foo = (props: FooProps) => {
const { bar, children } = props;
return (
<div>
<span>{bar}</span>
{children}
</div>
);
};

直接搭配物件的解構賦值:

// Object
export default function Post({
postData,
}: {
postData: {
title: string;
date: string;
contentHtml: string;
};
}) {
// ...
}

Array of object:

// array of object
export default function Home({
allPostsData,
}: {
allPostsData: {
date: string;
title: string;
id: string;
}[];
}) {
// ...
}

(不建議)使用 React.FC 預設就可以使用 ...restchildren

type Props = {
className?: string;
onSidebarOpen: React.MouseEventHandler;
};

const TopBar: React.FC<Props> = ({ className, children, ...rest }) => {
//...
};

div

讓 div 可以傳遞 title 這個 props 進來:

import React, { HTMLAttributes } from 'react';

export interface IBorderedBoxProps extends HTMLAttributes<HTMLDivElement> {
title: string;
}

const BorderedBox: React.FunctionComponent<IBorderedBoxProps> = ({
children,
title,
...divAttributes
}) => {
return (
<div {...divAttributes} style={{ border: '1px solid red' }}>
<h1>{title}</h1>
{children}
</div>
);
};

export default BorderedBox;

在其他 component 使用:

<BorderedBox title="Hello" onClick={() => alert('Hello')} />

Button

import React, { ButtonHTMLAttributes } from 'react';

interface IButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
/** The text inside the button */
text: string;
/** The type of button, pulled from the Enum ButtonTypes */
type: ButtonTypes;
/** The function to execute once the button is clicked */
action: () => void;
}

// 透過自己定義的 type 來延伸 Functional Component 這個型別
const ExtendedButton: React.FC<IButtonProps> = ({ text, type, action }: IButtonProps) => {};

Hooks

const [user, setUser] = React.useState<IUser>(user);
const [user, setUser] = React.useState<IUser | null>(null);

Events

從事件中取得 Event 物件:

import React, { MouseEvent } from 'react';

// 在 MouseEvent 後要記得帶入對應的 HTML 元素型別
function eventHandler(event: MouseEvent<HTMLAnchorElement | HTMLButtonElement | HTMLDivElement>) {
console.log('TEST!', event);
}

使用:

<BorderedBox title="Hello" onClick={eventHandler} />

Hooks

參考