1、首先我们先创建一个react项目,react官网也有react项目搭建的命令
npx create-react-app my-app
cd my-app
2、安装我们项目需要的样式依赖,这个项目理我用的是styled-components
yarn add styled-components
3、安装typescript的依赖命令
yarn add typescript @types/node @types/react @types/react-dom @types/jest
4、初始化typescript
tsc --init
5、将src里面的文件删除只剩index.js,并将App.js改为App.tsx
index.js代码如下:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
6、在App.tsx里面写一些简单的ts代码就可以run了
import React, { Component } from 'react'; interface Props { } interface State { list: string, } class App extends Component<Props, State> { constructor(props: Props) { super(props) this.state = { list: 'hello world!!!' } } render() { return ( <div> {this.state.list} </div> ); } } export default App;
7、运行项目执行命令: yarn start