我的第一部分
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
interface AppProps {
name: string;
}
interface AppState {
words: string[];
}
class App extends Component<AppProps, AppState> {
constructor() {
super();
this.state = {
words: ['foo', 'bar']
};
}
render() {
const { name } = this.props;
return (<h1>Hello {name}!</h1>);
}
}
const root = document.getElementById('root');
ReactDOM.render(<App name="Foo Bar" />, root);
將 TypeScript 與 React 一起使用時,一旦下載了 React DefinitelyTyped 型別定義(npm install --save @types/react
),每個元件都會要求你新增型別註釋。
你這樣做:
class App extends Component<AppProps, AppState> { }
其中 AppProps
和 AppState
分別是元件的 props 和 state 的介面(或型別別名)。