PJCHENder 未整理筆記

[TS] React Snippets of TypeScript

2020-06-17

[TS] React Snippets of TypeScript

Create React App

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

Functional Component

JSX

使用 React.FC 預設就可以使用 ...restchildren

1
2
3
4
5
6
7
8
type Props = {
className?: string;
onSidebarOpen: React.MouseEventHandler;
};

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

div

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 使用:

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

Button

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

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

Events

從事件中取得 Event 物件:

1
2
3
4
5
6
7
8
import React, { MouseEvent } from 'react';

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

使用:

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

Hooks

參考

掃描二維條碼,分享此文章