
Let’s say we are working in React Native and we need to convert the sample code of the ButtonGroup element from JavaScript to TypeScript with state handling. The code is taken from here and is an element of the React Native component module 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}}
/>
)
}
}
This code for handling the click state of a ButtonGroup in TypeScript will be as follows
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}}
/>
);
}
}