Оценок пока нет Конвертация класса компонента из JavaScript в TypeScript

Допустим, мы работаем в React Native и нам нужно преобразовать пример кода элемента ButtonGroup из JavaScript в TypeScript с обработкой состояния. Код взят отсюда и является элементом модуля компонентов React Native react-native-elements

import { ButtonGroup } from 'react-native-elements';
import * as React from 'react';
...
class BtnGroup extends React.Component{
 constructor () {
   super()
   this.state = {
     selectedIndex: 2
   }
   this.updateIndex = this.updateIndex.bind(this)
 }

 updateIndex (selectedIndex) {
   this.setState({selectedIndex})
 }

 render () {
   const buttons = ['Hello', 'World', 'Buttons']
   const { selectedIndex } = this.state

   return (
     <ButtonGroup
       onPress={this.updateIndex}
       selectedIndex={selectedIndex}
       buttons={buttons}
       containerStyle={{height: 100}}
     />
   )
 }
}

Данный код обработки состояния нажатия ButtonGroup в TypeScript будет следующим

import { ButtonGroup } from 'react-native-elements';
import * as React from 'react';
...

interface IProps {
}

interface IState {
  selectedIndex?: number;
}

class BtnGroup extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
        selectedIndex: 0
    }
    this.updateIndex = this.updateIndex.bind(this)
  }

  updateIndex (selectedIndex : number) {
      console.log(selectedIndex)
    this.setState({selectedIndex})
  }

  render() {
    const buttons = ['Мои программы', 'Мои упражнения']
    return(
        <ButtonGroup
        onPress={this.updateIndex}
        selectedIndex={this.state.selectedIndex}
        buttons={buttons}
        containerStyle={{height: 40}}
      />
    );
  }
}

Пожалуйста, оцените материал

WebSofter

Web - технологии