【发布时间】:2022-01-27 08:49:44
【问题描述】:
我正在使用 Expo 开发一个 React Native 项目。我定义了一个名为setRoleColors 的函数,它根据变量角色设置一些颜色。
export const setRoleColors = (role: string) => {
switch (role) {
case "student":
return { backgroundColor: Color.maroon.dark, color: "#fff" };
case "moderator":
return { backgroundColor:"#00ff00", color: "#000"};
case "user":
return { backgroundColor:"#0000ff", color: "#fff";
}
};
我将函数setRoleColors 导入到一个名为UserRole 的组件中。
import React from "react";
import { Text, View } from "react-native";
import { setRoleColors } from "../../services/SetRoleColors";
import styles from "./styles";
const UserRole: React.FC<{ role: string }> = ({ role }) => {
const { backgroundColor, color } = setRoleColors(role);
return (
<View style={{ ...styles.roleContainer, backgroundColor }}>
<Text style={{ ...styles.roleText, color }}>{role}</Text>
</View>
);
现在,一切正常,但是 VS Code 在 const { backgroundColor, color } = setRoleColors(role); 行中强调了两个变量 backgroundcolor 和 color,当我将鼠标悬停在它们上面时,它会显示一条消息,告诉我以下内容:
Property 'backgroundColor' does not exist on type'{backgroundColor: string; color: string} | undefined
Property 'color' does not exist on type'{backgroundColor: string; color: string} | undefined
【问题讨论】:
-
它没有。该值可能未定义,在这种情况下,属性访问将失败。编译器会告诉你完全正确的事情。
标签: reactjs typescript react-native