React + TS 项目搭建

969 阅读1分钟

楼主目前的公司大面积使用react + ts的架构开发前端了,所以不得已需要学习下最新的知识。

1. 搭建React + TS项目

设置国内yarn代理:

yarn config set registry https://registry.npm.taobao.org

移除原代理

yarn config delete proxy
npm config rm proxy
npm config rm https-proxy

安装cnpm镜像并使用代理registry

安装cnpm镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
使用代理registry
npm config set registry https://registry.npm.taobao.org

初始化项目:

yarn create react-app react-ts --template=typescript

启动项目

cd react-ts && yarn start

image.png

2. 修改App.tsx

使用ts类的形式修改主函数

import React, { Component } from 'react';
import './App.css';
​
class App extends Component<any, any>{
  render(){
    return (
      <>
        helloworld
      </>
    )
  }
}
​
export default App;

image.png git链接:

gitee.com/MY-WT/react…

3. 创建函数式组件

快捷键:rfc

import React from 'react';
​
const Lee = () => {
  return (
    <div>
      mytaowu
    </div>
  );
}
​
export default Lee;

App.tsx中进行引用

import React, { Component } from 'react';
import Lee from './Lee'class App extends Component<any, any>{
  render(){
    return (
      <>
        helloworld
        <Lee></Lee>
      </>
    )
  }
}
​
export default App;
​