【问题标题】:Adding type annotations to JSX, mistakes the type for a JSX tag向 JSX 添加类型注释,错误的类型为 JSX 标记
【发布时间】:2018-06-07 18:08:20
【问题描述】:

我正在尝试将这种风格的流类型注释添加到我的组件中(来自React typeReference

class Foo extends React.Component<{}> {}
function Bar(props: {}) {}

(<Foo />: React.Element<typeof Foo>); // OK
(<Bar />: React.Element<typeof Bar>); // OK
(<Foo />: React.Element<typeof Bar>); // Error: Foo is not Bar

我的尝试:

import React, { Component } from 'react'
import type { Node, Element } from 'react'

class AlertModalComponent extends Component<iAlertModal, State> {
  render(): Node {
    return (
      <View style={alertModalStyle.container}>
        (<PresentationalModal
          style={{ backgroundColor: 'transparent' }}
          isOpen={this.props.isOpen}
          title={this.props.title}
          message={this.props.message}
          updateAlertModalHeight={this.props.updateAlertModalHeight}
          viewHeight={this.props.viewHeight}
          hasYesNo={this.props.hasYesNo}
          yesClicked={this.props.yesClicked}
          updateAlertModalIsOpen={this.props.updateAlertModalIsOpen}
        />: Element<typeof PresentationalModal>)
      </View>
    )
  }
}

// $FlowFixMe
export default connect(mapStateToProps, mapDispatchToProps)(AlertModalComponent)

AlertModalComponent.contextTypes = {
  store: PropTypes.object
}

const PresentationalModal: Function = ({
  isOpen,
  title,...
}: AlertModal) => {
  console.log('presentational modal yes no')
  return (
    <Modal style={alertModalStyle.modal} isVisible={isOpen}>
...

错误:

&lt;typeof&gt; 的预期对应 JSX 结束标记

它认为&lt;typeof&gt; 是一个jsx 标签。这个错误的解决方法是什么?

【问题讨论】:

    标签: reactjs react-native jsx flowtype


    【解决方案1】:

    jsx中间不能加流类型注解。你需要像这样把它拉到外面

    render(): Node {
      const presentationalModel: Element<typeof PresentationalModal> = (
        <PresentationalModal
          style={{ backgroundColor: 'transparent' }}
          isOpen={this.props.isOpen}
          title={this.props.title}
          message={this.props.message}
          updateAlertModalHeight={this.props.updateAlertModalHeight}
          viewHeight={this.props.viewHeight}
          hasYesNo={this.props.hasYesNo}
          yesClicked={this.props.yesClicked}
          updateAlertModalIsOpen={this.props.updateAlertModalIsOpen}
        />
      )
      return (
        <View style={alertModalStyle.container}>
          {presentationalModal}
        </View>
      )
    }
    

    您是否有理由要显式键入此内容?添加此类型定义不会使您的代码更安全; flow 已经知道&lt;PresentationModal ... /&gt; 是一个PresentationModal 类型。似乎它增加了混乱。

    【讨论】:

    • 嗯,很公平。在我的顶级示例中,类型注释不是从 react 类型引用添加到 JSX 中吗?
    • 不同之处在于,上面的例子中,输入的是整个 jsx 值,而不起作用的那个是在 jsx 表达式的中间。
    猜你喜欢
    • 2019-07-21
    • 2018-08-12
    • 2020-04-29
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2022-07-12
    相关资源
    最近更新 更多