首页 > 解决方案 > 将 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 组件?

标签: reactjstypescript

解决方案


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 也有枚举和泛型类型。


推荐阅读