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

2023 年 WordPress 中最棒的多語言翻譯外掛推薦

擔心如何翻譯您的網站語言以支持…

1年 ago

2023 年 WordPress 中最棒的可視化頁面構建器外掛推薦

在設計任何頁面或網站時,對於不…

1年 ago

Ella 多用途 Shopify 佈景主題

Shopify 佈景主題市場上有許…

1年 ago

AI Engine Pro

喵容今天帶來的 AI Engi…

1年 ago

AIKit

喵容今天為您帶來 AIKit …

1年 ago

AIomatic

喵容今天為您帶來AIOmati…

1年 ago