【问题标题】:Text and TouchableOpacity Style Type AnnotationsText 和 TouchableOpacity 样式类型注解
【发布时间】:2017-12-06 10:34:45
【问题描述】:

我正在尝试使用 Flow 对我的 React Native 项目进行类型注释,但我无法找到 Text 和 TouchableOpacity 元素的类型定义,因此我可以引用它们的 style 道具类型定义。如何导入和/或引用这些元素的类型定义?

代码如下:

// @flow
import * as React from "react";
import { Text, TouchableOpacity } from "react-native";

type Props = {
    segmentIndex: number,
    segmentInfo: {
        title: string
    },
    segmentStyle: ???, // WHAT SHOULD I USE HERE?
    titleStyle: ???, // WHAT SHOULD I USE HERE?
    onSelection: (number) => void
}

export const SegmentButton = (props: Props) => {
    const _segmentPressed = () => {
        props.onSelection(props.segmentIndex)
    }

    return (
        <TouchableOpacity style={props.segmentStyle} onPress={_segmentPressed}>
            <Text style={props.titleStyle}>{props.segmentInfo.title.charAt(0).toUpperCase() + props.segmentInfo.title.substring(1)}</Text>
        </TouchableOpacity>
    )   
}

【问题讨论】:

    标签: react-native flowtype


    【解决方案1】:

    有很多方法可以定义StyleSheet 类型。

    1。 react-native 通用方式

    来自 react-native 库的引用,

    SwipeableQuickActionButton.js

    import { View } from 'react-native';
    
    type Prop = {
        style?: ?View.propTypes.style,
    }
    

    2。 react-navigation 通用方式

    来自 react-navigation 库的引用,

    TypeDefinition.js

    export type Style =
      | { [key: string]: any }
      | number
      | false
      | null
      | void
      | Array<Style>;
    

    如果您已经安装了react-navigation,请从以下位置导入:

    import type { Style } from 'react-navigation/src/TypeDefinition';
    
    type Prop = {
        style?: Style,
    }
    

    或者您仍然可以通过在自己的文件中定义来使用它。

    3。使Style 类型特定于&lt;Text /&gt; 和&lt;TouchableOpacity /&gt;

    这将是一种艰难的方式——虽然可行,但看看这是否值得。

    以&lt;Picker /&gt; 为参考,它为&lt;Text /&gt; 定义了itemStyle,如下所示,对应于每个选择器项的文本样式。

    var StyleSheetPropType = require('StyleSheetPropType');
    var TextStylePropTypes = require('TextStylePropTypes');
    var TextStyle = StyleSheetPropType(TextStylePropTypes);
    
    type Prop = {
        itemStyle: TextStyle
    }
    

    要在您自己的库中使用它,请从以下位置导入它们:

    import TextStylePropTypes from 'react-native/Libraries/Text/TextStylePropTypes';
    import StyleSheetPropType from 'react-native/Libraries/StyleSheet/StyleSheetPropType';
    
    let TextStyle = StyleSheetPropType(TextStylePropTypes);
    
    type Prop = {
        style?: ?TextStyle,
    }
    

    【讨论】:

    • @BryanSills 我的错误,没有仔细阅读您的问题。更新了我的答案。
    猜你喜欢
    • 2013-06-17
    • 2012-05-20
    • 2017-06-03
    • 2018-02-05
    • 2019-08-06
    • 2011-10-25
    • 1970-01-01
    • 2014-11-19
    • 2014-05-26
    相关资源
    最近更新 更多