Search code examples
typescriptreact-nativeattributes

ReactNative extended button props undefined


I try extend a Button component with a signature attribute to store specific data and add Button specific parameter to fetch. Why event.currentTarget.props is undefined?

import React from 'react';
import {
  Alert,
  Button,
  ButtonProps,
  GestureResponderEvent,
  StyleSheet,
  View,
} from 'react-native';

interface MyButtonProps extends ButtonProps {
  signature: string;
}
class MyButton extends React.Component<MyButtonProps, {}> {
  render() {
    return <Button {...this.props} />;
  }
}

const App = () => {
  const _onPressButton = (event: GestureResponderEvent) => {
    Alert.alert(JSON.stringify(event.currentTarget.props));
    //let params: string = (event.target as MyButton).props.signature;
    //fetch(`http://12.18.1.11/switch?${params}`);
  };

  return (
    <View style={styles.container}>
      <View style={styles.buttonContainer}>
        <MyButton
          signature="binary=000011110000011&protocol=1&pulselength=133"
          onPress={_onPressButton}
          title="LED1 (ON)"
        />
      </View>
      <View style={styles.buttonContainer}>
        <MyButton
          signature="binary=000111110&protocol=1&pulselength=133"
          onPress={_onPressButton}
          title="LED1 (OFF)"
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  buttonContainer: {
    margin: 20,
  },
});

export default App;

Maybe I not understand well the extension mechanism? Please help me.


Solution

  • I reorganized the code with a method call:

    class MyButton extends React.Component<MyButtonProps, {}> {
      _onPressButton = (params: string) => {
        fetch(`http://10.0.1.119/switch?${params}`);
      };
    
      render() {
        return (
          <Button
            onPress={() => this._onPressButton(this.props.signature)}
            {...this.props}
          />
        );
      }
    }