带打字稿的ES6箭头功能

时间:2019-08-09 20:04:48

标签: javascript reactjs typescript react-native

是Typescript的全新功能, 我不确定如何使这项工作。

进行了一些诸如破坏性研究之类的研究,但仍然无法解决问题。

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;

以下错误:

(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; }>'

3 个答案:

答案 0 :(得分:2)

明确指定“容器”的类型。您可以从ViewStyle包中使用通用的react-native类型:

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;

答案 1 :(得分:1)

您应该添加样式变量的类型

import React from "react";
import { StyleSheet, Text, View } from "react-native";

type Style = {
  [key: string]: Object;
};

type ViewStyles = {
  container: Style;
};

const styles: ViewStyles = {
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
};

const App: React.SFC = () => {
  const { container }: Style = styles;
  return (
    <View style={container}>
      <Text>Open up App.tsx to start working on your app!</Text>
    </View>
  );
};

export default App;

答案 2 :(得分:1)

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不支持Typescript,因此请确保在package.json中安装了@ typescript / react。