reactjs - 将 JavaScript React 组件转换为 TypeScript
问题描述
我打算将我拥有的一个 JavaScript 组件转换为 TypeScript,但我是 TypeScript 的新手,我不知道从哪里开始将我的 JavaScript 组件转换为 TypeScript。
我只将组件的主要部分放入我的问题中,但简要地我的组件包括:
我的组件:
class App extends React.Component {
state = { sections: [
{
"title": "Popular",
"items": [
{
"name": "Lorem",
"online": true,
} ]
}
]
}
render() {
var sections = this.state.sections.map(function(section, index) {
return (
<div className="container-fluid">
<Section section={section} key={index}/>
</div>
)
});
return(
<div> {sections} </div>
)
}
}
export default App;
我怎样才能在 TypeScript 中拥有这个 JavaScript 组件?
解决方案
class App extends React.Component {
state: ComponentState = {
sections: [
{
"title": "Popular",
"items": [
{
"name": "Lorem",
"online": true,
}
]
}
]}
render() {
var sections = this.state.sections.map(function(section, index) {
return (
<div className="container-fluid">
<Section section={section} key={index}/>
</div>
)
});
return(
<div> {sections} </div>
)
}
}
interface ComponetState {
sections?: {
title: string
online: boolean
}[]
}
}
export default App;
使用 typescript 的主要好处是它使 javascript 严格类型化。如您所见,我有界面ComponentState
。该接口是一种可以分配给变量的类型。这就是我对你的state
变量所做的。如您所见,界面的形状描述了可以处于您状态的数据。所有可选数据都用?
界面中其名称旁边的字符表示。
Typescript 也有枚举和泛型类型。
推荐阅读
- r - 在r上的数据框中减去日期列
- ruby-on-rails - 为什么我的 HTTP Origin 标头与 request.base_url 不匹配,如何解决?
- nuxt.js - nuxt-link 在 nuxt-child 的父级中打开页面
- r - 当矩阵太大而无法进行常规操作时,如何删除 DFM 中的零项?
- android - Firebase:您请求的项目无法购买
- selenium - 我的硒网络刮刀对我来说没有意义
- excel - 反转行顺序
- flutter - 如何对列表进行排序
- javascript - Javascript 在粘贴时捕获特殊字符,特别是 TAB
- spring - 在存储库中声明自定义方法时,我们应该遵循哪些规则?