0

我有一个 React 界面,例如:TextStyle。而且我需要使用像 textAlign 这样的动态值。但是这个文本对齐必须匹配接口枚举。我该怎么做呢?

我试过了typeof TextStyle["textAlign"],但我得到了'TextStyle' only refers to a type, but is being used as a value here.

// @see https://facebook.github.io/react-native/docs/text.html#style
export interface TextStyle extends TextStyleIOS, TextStyleAndroid, ViewStyle {
    color?: string;
    fontFamily?: string;
    fontSize?: number;
    fontStyle?: "normal" | "italic";
    /**
     * Specifies font weight. The values 'normal' and 'bold' are supported
     * for most fonts. Not all fonts have a variant for each of the numeric
     * values, in that case the closest one is chosen.
     */
    fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900";
    letterSpacing?: number;
    lineHeight?: number;
    textAlign?: "auto" | "left" | "right" | "center" | "justify";
    textDecorationLine?: "none" | "underline" | "line-through" | "underline line-through";
    textDecorationStyle?: "solid" | "double" | "dotted" | "dashed";
    textDecorationColor?: string;
    textShadowColor?: string;
    textShadowOffset?: { width: number; height: number };
    textShadowRadius?: number;
    testID?: string;
}

我想从 TextStyle 界面中提取枚举以拥有type TextAligEnum = "auto" | "left" | "right" | "center" | "justify";

例如:

const renderX = ({
  title = "title",
  textAlign = "center"
}: {
  title: string;
  textAlign?: typeof TextStyle["textAlign"];
                     ^^^^^^^^^ 'TextStyle' only refers to a type, but is being used as a value here.
}) => {
  return (
      <Text style={{ textAlign }]}>
        {title.toUpperCase()}
      </Text>

  );
};
4

2 回答 2

4

您不需要typeof,只需单独使用即可TextStyle["textAlign"]

const renderX = ({
  title = "title",
  textAlign = "center"
}: {
  title: string;
  textAlign?: TextStyle["textAlign"];
}) => {
  return (
      <Text style={{ textAlign }]}>
        {title.toUpperCase()}
      </Text>

  );
};

typeof接受一个值的标识符并返回其类型。但是TextStyle已经是一个类型,这就是为什么它不能与 typeof 一起使用。

于 2019-08-07T18:21:50.583 回答
1

您可以TextStyle["textAlign"]用作类型:

interface TextStyle {
    color?: string;
    fontFamily?: string;
    fontSize?: number;
    fontStyle?: "normal" | "italic";
    fontWeight?: "normal" | "bold" | "100" | "200" | "300" | "400" | "500" | "600" | "700" | "800" | "900";
    letterSpacing?: number;
    lineHeight?: number;
    textAlign?: "auto" | "left" | "right" | "center" | "justify";
    textDecorationLine?: "none" | "underline" | "line-through" | "underline line-through";
    textDecorationStyle?: "solid" | "double" | "dotted" | "dashed";
    textDecorationColor?: string;
    textShadowColor?: string;
    textShadowOffset?: { width: number; height: number };
    textShadowRadius?: number;
    testID?: string;
}


const a1: TextStyle["textAlign"] = "left"; // ok
const a2: TextStyle["textAlign"] = "center"; // ok
const a3: TextStyle["textAlign"] = "middle";  // error 
于 2019-08-07T18:26:26.243 回答