React TypeScript 開發實踐

一、基礎知識

React is a JavaScript library for building user interfaces.
It is maintained by Facebook and a community of individual developers and companies.
React allows developers to create reusable UI components and is widely used in web and mobile app development.
TypeScript is a programming language that is a superset of JavaScript and adds static typing, interfaces, and other features to the language.
TypeScript enhances the development experience in React by providing type checking and improving code readability and maintainability.
With TypeScript, it is easier to catch errors during development and refactor code as projects grow in complexity.

在安裝 TypeScript 時,可以選擇直接使用 create-react-app 腳手架。在使用 create-react-app 時加上 –template typescript 參數即可:

npx create-react-app my-app --template typescript

二、函數組件

React 中的函數組件是一種無狀態的組件,可以通過函數輸入來返回 JSX 元素。
在 TypeScript 中,函數組件需要使用泛型來定義輸入的類型和返回值的類型。


interface Props {
  name: string;
}

const Greeting: React.FC = ({name}) => (
  <div>Hello {name}</div>
);

在函數組件中,React 提供了一些 hooks 來實現組件狀態管理和生命周期管理。
在 TypeScript 中,需要根據 hooks 的類型來定義與 hooks 相關的變量和參數類型。


import React, { useState, useEffect } from 'react';

interface Props {
  name: string;
}

const Greeting: React.FC = ({name}) => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <div>Hello {name}! You clicked {count} times.</div>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

三、類組件

React 中類組件繼承自 React.Component 類,可以使用類屬性和生命周期方法來管理組件狀態和生命周期。
在 TypeScript 中,需要定義 Props 和 State 接口來規範輸入和狀態的類型。


interface Props {
  name: string;
}

interface State {
  count: number;
}

class Greeting extends React.Component {
  constructor(props: Props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <div>Hello {this.props.name}! You clicked {this.state.count} times.</div>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

四、組件通信

在 React 中,組件間的通信可以通過 props 和 Context API 來實現。
在 TypeScript 中,需要定義接口來規範 props 和 context 的類型。


interface AppProps {
  title: string;
}

const App: React.FC<AppProps> = ({title}) => (
  <div>
    <Header title={title} />
    <Main />
  </div>
);

interface HeaderProps {
  title: string;
  subtitle?: string;
}

const Header: React.FC<HeaderProps> = ({title, subtitle}) => (
  <div>
    <h1>{title}</h1>
    {subtitle && <h2>{subtitle}</h2>}
  </div>
);

interface ThemeContextProps {
  theme: 'light' | 'dark';
}

const ThemeContext = React.createContext<ThemeContextProps>({
  theme: 'light',
});

const Main: React.FC = () => (
  <div>
    <ThemeContext.Provider value={{ theme: 'light' }}>
      <Content />
    </ThemeContext.Provider>
  </div>
);

const Content: React.FC = () => {
  const { theme } = React.useContext(ThemeContext);
  return (
    <div style={{ backgroundColor: theme === 'light' ? 'white' : 'black', color: theme === 'light' ? 'black' : 'white' }}>
      <p>This is the main content.</p>
    </div>
  );
};

五、組件庫

在 React 中,組件庫可以幫助開發者快速搭建項目 UI。
Ant Design 是一個流行的開源組件庫,提供了豐富的 UI 組件和可配置的樣式主題,適用於 Web 和移動端項目。
在 TypeScript 中,Ant Design 提供了 Typed API 來提供完整的類型推斷和代碼提示。


import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'antd';

ReactDOM.render(<Button type="primary">Click me!</Button>, document.getElementById('root'));

六、總結

React TypeScript 是一種支持靜態類型檢查的開發方式,可以提高項目的可維護性和開發效率。
在 React TypeScript 開發中,可以使用函數組件和類組件來實現組件狀態和生命周期管理,使用 props 和 Context API 來實現組件通信,使用組件庫來快速搭建項目 UI。
使用 TypeScript 可以更好地規範和管理代碼,減少代碼錯誤和維護成本。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/291249.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-24 13:14
下一篇 2024-12-24 13:14

相關推薦

  • @uiw/react-amap介紹

    本文將詳細闡述@uiw/react-amap的使用方法和參數配置,以及如何在React應用中集成高德地圖組件。 一、@uiw/react-amap簡介 @uiw/react-ama…

    編程 2025-04-29
  • Webrtc音視頻開發React+Flutter+Go實戰PDF

    本文將從多個方面介紹如何使用React、Flutter和Go來進行Webrtc音視頻開發,並提供相應的代碼示例。 一、Webrtc音視頻開發介紹 Webrtc是Google開發的一…

    編程 2025-04-27
  • React簡書項目

    本文將從以下幾個方面介紹React簡書項目: 項目概述 組件分析 路由配置 Redux狀態管理 項目優化 一、項目概述 React簡書項目是一個類似於博客的Web應用,提供用戶撰寫…

    編程 2025-04-27
  • React-Icons:強大的圖標庫

    一、React-Icons的介紹 React-Icons 是一個可重用的 React 組件集合,構建了一組常見的圖標,可用於任何 React.js 項目。它為所有的圖標提供了友好的…

    編程 2025-04-25
  • TypeScript declare詳解

    一、declare語句的作用 1、文字闡述內容:TypeScript中的declare語句是用來定義變量、函數、類等外部代碼塊的類型。它告訴TypeScript編譯器某個變量實際上…

    編程 2025-04-25
  • TypeScript中的foreach循環

    一、概述 JavaSript是一門靈活的語言,其中的數組也同樣靈活多變。這就使得在一個數組上執行某些操作變得很方便。其中,forEach()就是用來遍曆數組的。 在TypeScri…

    編程 2025-04-24
  • React 子組件調用父組件方法

    一、基本介紹 React 是一個非常流行的 JavaScript 庫,用於構建用戶界面。React 的主要思想是組件化,允許將 UI 拆分為獨立的、可復用的部分。React 組件有…

    編程 2025-04-23
  • useMemo——提高React性能的利器

    一、什麼是useMemo React中提供了一種優化組件性能的鉤子函數——useMemo。它可以幫助我們避免在每次渲染時都執行的昂貴計算。 useMemo鉤子函數接收兩個參數:計算…

    編程 2025-04-23
  • Flutter和React Native的比較

    一、性能比較 Flutter是Google推出的移動端UI框架,最初是為了高性能而設計的。它使用Dart編寫,具有JIT和AOT兩種編譯模式,可以更好地優化性能。相比之下,Reac…

    編程 2025-04-23
  • React Context 實現原理詳解

    一、Context是什麼? Context是React提供的一種跨組件層級共享數據的方式。它解決了React組件之間數據傳遞的諸多問題。 1.1 基本用法 const ThemeC…

    編程 2025-04-23

發表回復

登錄後才能評論