【问题标题】:Create Generic Custom Component React创建通用自定义组件 React
【发布时间】:2020-07-02 08:02:51
【问题描述】:

这是 react-native 问题,但类似的概念也可以应用于 react。

我想在 react-native 中创建一个 CustomView。我正在使用打字稿。

到目前为止,我有:

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#ffffff',
    borderRadius: 10,
  }
});

type CustomViewProps= {
  width: number,
  height: number,
  marginTop?: string | number,
}

const CustomView = ({ width, height, marginTop }: CustomViewProps) => (
  <View style={[styles.container, { height, width, marginTop }]} />
);

到目前为止还可以,因为只使用了 3 个道具:width、height 和 marginTop。

但是,这是不可重复使用的,如果我需要添加更多道具,它可能会变得冗长。

所以,问题是:如何让 CustomView 接收任何 props 作为原生组件 View 可以接收的?

我的猜测是我应该删除 CustomViewProps。然后,我应该让 props 继承自原生组件 View 的相同类型。但是,我正在为此苦苦挣扎。

【问题讨论】:

    标签: javascript reactjs typescript react-native types


    【解决方案1】:

    由于您正在创建CustomViewProps,我假设您希望在该组件的已编写行为之上添加一些特定行为到您的本机组件。

    让我们创建一个示例。

    我想创建一个具有某些特定行为的按钮,但我希​​望它在其他情况下表现得像普通的TouchableOpacity 组件。例如,我想添加一个“加载”状态,它将在内部显示一个加载器而不是它的内容。 所以逻辑是:创建您的自定义道具并将您的自定义道具与本机的默认道具合并

    import React, { FC, ReactElement } from 'react'
    import { ActivityIndicator, TouchableOpacity, TouchableOpacityProps, StyleSheet } from 'react-native'
    
    type MyProps = {
      loading?: boolean
      children: ReactElement
    }
    
    const MyButton: FC<MyProps & TouchableOpacityProps> = (props: MyProps & TouchableOpacityProps) => (
      <TouchableOpacity {...props} disabled={props.disabled || props.loading} style={[styles.button, props.style]}>
        {props.loading ? <ActivityIndicator /> : props.children}
      </TouchableOpacity>
    )
    
    const styles = StyleSheet.create({
      button: {
        backgroundColor: 'yellow',
        borderColor: 'black',
        borderWidth: 1,
        borderRadius: 10,
        padding: 10
      },
    })
    
    export default MyButton
    
    
    

    loading 属性将负责按钮的内容或者是disabled 属性。 TouchableOpacity 组件将接收每个兼容的道具(将启用自动建议,因为您已分配 TouchableOpacityProps)。 styles.button 的行为类似于默认样式,但如果您在 style 属性中指定不同的内容,则会被覆盖。就是这样!

    【讨论】:

    • 你的答案是金子。我只是将它应用到我的组件并得到它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多