# TypeScript react - 環境配置 hooks typescirpt: https://fettblog.eu/typescript-react/hooks/ ### 使用 typescript 的 react 專案 https://github.com/search?q=language%3ATypeScript+language%3ATypeScript+react&type=Repositories ### 安裝、建立專案 一個新專案 ``` npx create-react-app my-app --template typescript # or yarn create react-app my-app --template typescript ``` 在舊的專案中 create-react-app 中加入 TypeScript ``` npm install --save typescript @types/node @types/react @types/react-dom @types/jest # or yarn add typescript @types/node @types/react @types/react-dom @types/jest ``` tsconfig.json ```json { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react" }, "include": [ "src" ] } ``` -1 將 App.js 改成 App.tsx -2 `npm run start` -3 看 react-typescript-cheatsheet 相關語法 這裡提供網站給你 https://github.com/typescript-cheatsheets/react-typescript-cheatsheet https://jkchao.github.io/typescript-book-chinese/jsx/reactJSX.html#react-jsx-tip-%E5%8F%AF%E6%B8%B2%E6%9F%93%E7%9A%84%E6%8E%A5%E5%8F%A3 hooks typescirpt: https://fettblog.eu/typescript-react/hooks/ ### vscode 設定 #### vscode.setting ```json "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, ``` #### prettier ```json { "bracketSpacing": true, "jsxBracketSameLine": true, "printWidth": 80, "singleQuote": true, "trailingComma": "none", "semi": false, "tabWidth": 2, "useTabs": false, "react/jsx-max-props-per-line": [1, { "when": "always" }] } ``` #### .editorconfig ``` root = true [*.tsx] end_of_line = lf insert_final_newline = true charset = utf-8 [*.tsx] indent_style = space indent_size = 2 [Makefile] indent_style = tab ``` ### create react app 設定 ts .env ``` TSC_COMPILE_ON_ERROR=true ``` ### React TypeScript type 整理 #### class component ```jsx type Props = { foo: string; }; class MyComponent extends React.Component<Props, {}> { render() { return <span>{this.props.foo}</span>; } } <MyComponent foo="bar" />; ``` #### function component ```jsx type Props = { foo: string; }; const MyComponent: React.FunctionComponent<Props> = props => { return <span>{props.foo}</span>; }; <MyComponent foo="bar" />; ``` #### html 標籤 React.ReactNode `<h1>1234</h1>` ```jsx type Props = { header: React.ReactNode; body: React.ReactNode; }; class MyComponent extends React.Component<Props, {}> { render() { return ( <div> {this.props.header} {this.props.body} </div> ); } } <MyComponent header={<h1>Header</h1>} body={<i>body</i>} /> ``` #### e.preventDefault() ```jsx const sendMessage = (e: React.FormEvent<HTMLInputElement>) => { e.preventDefault() } ``` #### react-router-dom ``` yarn add @types/react-router-dom react-router-dom yarn add @types/react-router-dom@5.1.2 react-router-dom@5.1.2 //指定版本 ``` ```jsx // pages/Home/index.tsx import React from "react"; const Home: React.FunctionComponent = () => { return ( <div>123</div> ) }; export default Home; ``` ```jsx // App.tsx import React, { FunctionComponent } from "react"; import { Route, Switch, Link } from "react-router-dom"; import { ThemeProvider } from "@material-ui/styles"; import { Minimal as MinimalLayout } from "./layouts"; import theme from "./theme"; import "./App.css"; import "./styles/main.scss"; import Home from "./pages/home"; import SignIn from "./pages/SignIn"; type Props = { component: any, exact: boolean, layout: FunctionComponent, path: string } const RouteWithLayout: FunctionComponent<Props> = (props) => { const { layout: Layout, component: Component, ...rest } = props; return ( <Route {...rest} render={(matchProps: any) => ( <Layout> <Component {...matchProps} /> </Layout> )} /> ); }; function App() { return ( <ThemeProvider theme={theme} > <Switch> <Route exact path="/" > <Home /> </Route> <RouteWithLayout component={SignIn} exact layout={MinimalLayout} path="/signin" /> </Switch> </ThemeProvider> ); } export default App; ``` ### hook #### useRef https://linguinecode.com/post/how-to-use-react-useref-with-typescript ```jsx // <div> reference type const divRef = React.useRef<HTMLDivElement>(document.createElement('div')); // <button> reference type const buttonRef = React.useRef<HTMLButtonElement>(null); // <br /> reference type const brRef = React.useRef<HTMLBRElement>(null); // <a> reference type const linkRef = React.useRef<HTMLLinkElement>(null); // <input /> const linkRef = React.useRef<HTMLInputElement>(null); ``` 參考 https://github.com/typescript-cheatsheets/react-typescript-cheatsheet https://pjchender.blogspot.com/2020/07/typescript-react-using-typescript-in.html