ts:react中使用ts遇到的坑总结

编写一个 TSX 组件

import React from 'react' 
import ReactDOM from 'react-dom'

const App = () => {
 return (
  <div>Hello world</div>
 )
}
ReactDOM.render(<App />, document.getElementById('root')

上述代码运行时会出现以下错误
Cannot find module 'react'
Cannot find module 'react-dom'
错误原因是由于 React 和 React-dom 并不是使用 TS 进行开发的,所以 TS 不知道 React、 React-dom 的类型,以及该模块导出了什么,此时需要引入 .d.ts 的声明文件

安装 React、 React-dom 类型定义文件

yarn add @types/react @types/react-dom

有状态组件开发

import * as React from 'react';
interface IProps {
  color: string,
  size?: string,
}
interface IState {
  count: number,
}
class App extends React.Component<IProps, IState> {
  public state = {
    count: 1,
  }
  public render () {
    return (
      <div>Hello world</div>
    )
  }
}
发布了170 篇原创文章 · 获赞 59 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/104084676
ts