javascript - ES6-pilfunktion med Typescript
Extremt ny på Typescript, jag är inte säker på hur man får detta att fungera.
Gjorde lite forskning som destrukturering men kan fortfarande inte få det rätt.
import React from "react";
import { StyleSheet, Text, View } from "react-native";
const styles = {
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
}
};
const App = (style: any): {} => {
const { container } = styles;
return (
<View style={container}>
<Text>Open up App.tsx to start working on your app!</Text>
</View>
);
};
export default App;
Fel nedan:
(JSX attribute) style?: StyleProp<ViewStyle>
Type '{ flex: number; backgroundColor: string; alignItems: string; justifyContent: string; }' is not assignable to type 'StyleProp<ViewStyle>'.
Type '{ flex: number; backgroundColor: string; alignItems: string; justifyContent: string; }' is not assignable to type 'ViewStyle'.
Types of property 'alignItems' are incompatible.
Type 'string' is not assignable to type 'FlexAlignType'.ts(2322)
index.d.ts(2206, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'
Svar #1
Ange typ av "container" uttryckligen. Det finns en generell ViewStyle-typ du kan använda från react-native-paketet:
import React from "react";
import { StyleSheet, Text, View, ViewStyle } from "react-native";
const styles = {
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
} as ViewStyle
};
const App = () => {
const { container } = styles;
return (
<View style={container}>
<Text>Open up App.tsx to start working on your app!</Text>
</View>
);
};
export default App;
Svar #2
const styles = {
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
}
};
const App: React.SFC = () => {
return
<View style={styles.container}>
<Text>Open up App.tsx to start working on your app!</Text>
</View>
)
}
- React stöder inte Typescript som standard, så se till att du har @typescript/react installerat i din package.json
