首页 > 解决方案 > 用于自定义组件的 React Native VS Code Intellisense

问题描述

我在理解如何制作自定义组件时遇到了一些麻烦。我为自己制作了一个简单的 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;

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

标签: reactjsreact-nativevisual-studio-code

解决方案


您需要Props像这样定义道具类型绕过类内组件extends Component<Props> {

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;

推荐阅读