【问题标题】:React Native VS Code Intellisense for custom components用于自定义组件的 React Native VS Code Intellisense
【发布时间】:2021-06-21 08:17:51
【问题描述】:

我在理解如何制作自定义组件时遇到了一些麻烦。我为自己制作了一个简单的 Text 组件,以摆脱每次使用 Text 时设置 fontsize 和 fontfamily 的麻烦。

import React, { Component } from 'react';

import { Colors } from "../assets/Colors"
import { Text as RNText } from 'react-native';

class Text extends Component {
    render() {
        return (
            <RNText
                {...this.props}
                style={[{
                    fontFamily: 'Roboto-Medium',
                    fontSize: 16,
                    color: Colors.text
                }, this.props.style]}>
                {this.props.children}
            </RNText>
        )
    }
}

export default Text;

这里的问题是当我输入我自己的组件"&lt;Text style={{marginV" intelliSense 时不会弹出自动填充到marginVertical。此外,当我输入"&lt;Text onPre" intelliSense 时,也不会将自动完成弹出到 onPress。我对制作漂亮的组件感到非常兴奋,但如果没有智能感知,使用起来非常令人沮丧。我已经尝试过设置 proptypes 但它没有用。有什么快速解决办法吗?

【问题讨论】:

    标签: reactjs react-native visual-studio-code


    【解决方案1】:

    你需要定义 props 类型绕过 Props 像这样 extends Component&lt;Props&gt; { 的类内组件

    import React, { Component } from 'react';
    
    import { Colors } from "../assets/Colors"
    import { Text as RNText, StyleProp, ViewStyle } from 'react-native';
    
    type Props = {
        style: StyleProp<ViewStyle>
    }
    
    class Text extends Component<Props> {
        render() {
            return (
                <RNText
                    {...this.props}
                    style={[{
                        fontFamily: 'Roboto-Medium',
                        fontSize: 16,
                        color: Colors.text
                    }, this.props.style]}>
                    {this.props.children}
                </RNText>
            )
        }
    }
    
    export default Text;
    

    【讨论】:

    • 感谢您的回答,但我收到此错误:Type arguments can only be used in TypeScript files.ts(8011)
    • 我刚刚用这个网站typescriptlang.org/play解决了这个问题。但现在我有一个 Text.d.ts 文件和 Text.js 文件。有没有办法在一个文件中解决它?
    • @SickRanchez 您可以通过将文件扩展名 js 更改为 ts
    • 我已经尝试过了,但它会引发很多错误。我对 TS 还不是很熟悉,也不知道语法应该如何。我也找不到任何从 js 到 ts 的在线转换器。我有点卡住了
    • 那么你应该使用 Text.d.ts 方法
    猜你喜欢
    • 2018-01-17
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2023-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多