react native - Hur man åtgärdar detta fel med Props (ReactNative + Typescript)


Jag utvecklar min första app i react-native med TS och när jag försöker använda min komponent med props får jag ett fel i min IDE men applikationen fungerar med Expo...

Felet finns på "ButtonPreset"

import React from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import ButtonPreset from "./Components/reusable/ButtonPreset";

export interface ButtonPrefab {
  _pressAction(): void;
  pressAction(): void;
}

export default class App extends React.Component {
  _pressAction = () => {
    console.log("Hello");
  }

  title: string = "Se connecter";

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>Splizi</Text>
        </View>
        <View style={styles.login}>
          <TextInput style={styles.input} placeholder="E-mail" />
          <TextInput style={styles.input} placeholder="Mot de passe" />
          <ButtonPreset pressAction={this._pressAction} title={this.title} />
        </View>
      </View>
    );
  }
}
import React from "react";
import { StyleSheet, Button } from "react-native";

type ButtonPresetProps = {
  pressAction: () => void;
  title: string
}

class ButtonPreset extends React.Component<ButtonPresetProps> {
  render() {
    return <Button onPress={this.props.pressAction} title={this.props.title} />;
  }
}

const styles = StyleSheet.create({
  // input: {
  //     marginLeft: 40,
  //     marginRight: 40,
  //     marginBottom: 20,
  //     height: 60,
  //     borderRadius: 50,
  //     borderWidth: 0.5,
  //     paddingRight: 20,
  //     paddingLeft: 20,
  //     fontSize: 18,
  //     borderColor: '#d6d6d6',
  //     backgroundColor: '#ffffff',
  // }
});

export default ButtonPreset;

Jag får följande fel. Vänligen hjälp mig att lösa detta.

Typen '{ pressAction:() => void; title: string; }' kan inte tilldelas typen 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Egenskapen 'pressAction' finns inte på typen 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

Svar #1

Baserat på felmeddelandet behöver ButtonPreset en lämplig typ för sina egenskaper.

type ButtonPresetProps = {
  pressAction: () => void;
  title: string;
};

class ButtonPreset extends React.Component<ButtonPresetProps> {
  // other code omitted
}

Svar #2

export interface ButtonPrefab {
    _pressAction:() => void;
    pressAction:() => void;
}

export default class App extends React.Component<ButtonPrefab> {}

Prova detta.