简体   繁体   English

将 JavaScript React 组件转换为 TypeScript

[英]Converting JavaScript React Component into TypeScript

I am going to convert one JavaScript component I have, into TypeScript but I am new to TypeScript and I do not know where I have to start for converting my JavaScript component to TypeScript. I am going to convert one JavaScript component I have, into TypeScript but I am new to TypeScript and I do not know where I have to start for converting my JavaScript component to TypeScript.
I put just the main parts of component into my question but briefly my component includes:我只将组件的主要部分放入我的问题中,但简要地我的组件包括:

Mycomponent:我的组件:

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;

How can I have this JavaScript Component in TypeScript?我怎样才能在 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;

The primary benefit of using typescript is that it makes javascript strictly typed.使用 typescript 的主要好处是它使 javascript 严格类型化。 As you can see I have the interface ComponentState .如您所见,我有接口ComponentState This interface is a type that can be assigned to a variable.该接口是一种可以分配给变量的类型。 This is what I did to your state variable.这就是我对您的state变量所做的。 As you can see, the shape of the interface describes the data that can be in your state.如您所见,接口的形状描述了您的 state 中的数据。 All optional data is denoted with the ?所有可选数据都用? character next to its name in the interface.界面中其名称旁边的字符。

Typescript also has enums and generic types. Typescript 也有枚举和泛型类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM