代码之家  ›  专栏  ›  技术社区  ›  David Schumann Axnyff

使用react native中无状态功能组件的流定义属性类型

  •  3
  • David Schumann Axnyff  · 技术社区  · 7 年前

    我目前正在使用flow和eslint清理我们的代码库。

    Eslint告诉您将无状态组件转换为无状态功能组件。但我还没有找到一个例子来说明他们的道具是如何正确键入flow的。以下是我尝试的内容:

    原始组件:

    type Props = {onPress : Function}
    
    export default class MyButton extends React.Component <Props> {
      render() {
        ...  // use this.props.onPress
      }
    }
    

    版本1(我期望函数如何工作): 此处flow表示 Cannot create MyButton element because a callable signature is missing in props [1] but exists in function type [2].

    const MyButton = (onPress: Function) => (
      return(
        ...  // use onPress
      )
    }
    

    版本2(如所示 here ): eslint抱怨说 onPress 找不到。 ${onPress} 也不起作用。 流量投诉: Missing type annotation for destructuring.

    const MyButton = ({onPress: Function}) => (
      return(
        ...  // use onPress (or ${onPress} ??)
      )
    }
    

    那么我该如何解决这个问题呢?

    1 回复  |  直到 7 年前
        1
  •  4
  •   TLadd    7 年前

    您的版本2已关闭,但您无法在解构中定义类型;您必须定义整个对象类型。看起来像这样

    type Props = {
      onPress: Function
    }
    const MyButton = ({ onPress }: Props) => (
      return(
        ...
      )
    }