【问题标题】:Type issues with Dynamic StyleSheet property access动态样式表属性访问的类型问题
【发布时间】:2020-12-01 23:39:39
【问题描述】:

我创建了一个带有浅色和深色主题样式的 React Native 功能组件。

const lightThemeOverrides = StyleSheet.create({ <light_override_styles_here> });
const styles = StyleSheet.create({ <styles_here> });

我正在尝试借助函数在我的代码中使用它们:

const themedStyles = (key: string) => {
  if (props.theme === 'light') {
    return { ...styles[key], ...lightThemeOverrides[key] };
  } else {
    return styles[key];
  }  
};

我在我的 JSX 中这样使用这个函数:&lt;View style={themedStyles('popup')}&gt;

但我的 ts linter 在抱怨,Element implicitly has an 'any' type because type '{ popup: { backgroundColor: string; }; text: { color: string; }; }' has no index signature.

知道如何解决这个问题吗? 我们将不胜感激所有提示。

【问题讨论】:

    标签: typescript react-native types


    【解决方案1】:

    我目前的解决方案是像这样修改themedStyles 函数:

    const themedStyles = (key: 'popup' | 'text'): StyleProp<any> => {
      if (props.theme && props.theme === 'light') {
        return { ...styles[key], ...lightThemeOverrides[key] };
      } else {
        return styles[key];
      }  
    };
    

    密钥的类型为'popup' | 'text' 或类似。在lightThemeOverrides StyleSheet 中包含每个可能的键。

    我还将函数的类型设置为 StyleProp&lt;any&gt; 以修复 JSX 中的更多类型问题。

    虽然我不喜欢这个解决方案,因为必须为每个组件更改功能,但它确实可以。目前。任何进一步的 cmets 仍然欢迎:)

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多