一、基礎知識
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-hant/n/291249.html