JavaScript

解决Vscode开发React Native应用时编写Stylesheet没有智能代码提示的问题

文章转载务必带上原文地址!否则盗版必究。

问题描述

似乎Vscode原生对React Native的样式表代码提示有问题,所以在github找到了两个解决办法。

无代码提示:

解决后

以下两种办法亲测可用

解决办法一

首先在utils目录下创建工具类

import { StyleSheet as RnStyleSheet, ViewStyle, TextStyle, ImageStyle } from 'react-native';

type StyleProps = Partial<ViewStyle | TextStyle | ImageStyle>;

export const StyleSheet = {
    create(styles: { [className: string]: StyleProps }) {
        return RnStyleSheet.create(styles);
    }
};

然后在我的组件中

import { Stylesheet }  from './utils';

StyleSheet.create({
   "myClass": {
      // get intellisense for keys and values here
   }
});

当然,你需要扩展它以代理其他方法调用(flatten,…)到StyleSheet。

解决办法二

修改源码

找到npm install @types/react-native --save-dev and then open node_modules/@types/react-native/index.d.ts

或者ctrl+左键点击'react-native'进入

随后搜索export namespace StyleSheet {

删除源码中的create代码

替换为:

/**
  * Creates a StyleSheet style reference from the given object.
  */
export function create<T extends NamedStyles<T>>( styles: T | Style ): {
    [P in keyof T]: RegisteredStyle<T[P]>;
};

然后在刚刚的export namespace StyleSheet {上方添加以下代码,定义类型

type Style = ViewStyle | TextStyle | ImageStyle;
type NamedStyles<T> = {
    [P in keyof T]: Style;
}

至此,保存源代码,解决!去看看你的项目文件中有没有智能提示吧,反正我是有了,非常爽歪歪,上面两个办法都是通用的。

由此可见,提示的缺失可能是TS的类型声明问题。

参考自:https://github.com/Microsoft/vscode-react-native/issues/379

Recent Posts

Flexible Shipping Pro

在WordPress的世界里,…

3天 ago

2023 年 WordPress 中最棒的多语言翻译插件推荐

担心如何翻译您的网站语言以支持…

1年 ago

2023 年 WordPress 中最棒的可视化页面构建器插件推荐

在设计任何页面或网站时,对于不…

1年 ago

Ella 多用途 Shopify 主题

Shopify 主题市场上有许…

1年 ago

AI Engine Pro

喵容今天带来的 AI Engi…

1年 ago

AIKit

喵容今天为您带来 AIKit …

1年 ago