【问题标题】:Get keys from Flow object type in code在代码中从 Flow 对象类型中获取键
【发布时间】:2018-05-19 07:10:28
【问题描述】:

是否可以从应用代码中的流对象类型定义中获取键(换句话说,流类型定义是否在运行时代码中以任何方式具体化)?

用例:

type Props = {
  userID: string,
  size: number | PhotoSize,
  subscribePresence: Function,
  unsubscribePresence: Function,
  presenceStatus: ?PresenceStatus,
  photoURL: ?string,
  userName: ?string,
};

class Photo extends Component<Props> {
  // ...
  render() {
    const { userID, size, presenceStatus } = this.props;
    // Other props used elsewhere in the component
    const restProps = _.omit(this.props, ???)
  }
}

传播解构 (const { /* etc */ ... rest} = this.props) 不起作用,因为在 render 中没有使用其他道具。但是,我想选择其他可能已指定的道具(classNameid 等)。

??? 可以派生自类似于Object.keys(Props) 的东西吗?据我所知,类型定义已被编译掉,因此尝试在运行时代码中引用 Props 会引发 RuntimeError: Props is not defined

【问题讨论】:

  • 不,所有类型信息在编译时被剥离

标签: javascript reactjs webpack flowtype


【解决方案1】:

Flow 提供静态类型分析,所有 Flow 代码在运行前被剥离(流注解不是有效的 Javascript 代码)。

要实现您想要的,您需要在剥离 Flow 代码后获得有关预期 Props 的信息。您可以通过为组件中的所有道具设置defaultProps 来做到这一点,然后您可以编写:

const restProps = _.omit(this.props, Photo.defaultProps)

无论如何,设置 defaultProps 通常是个好主意。

【讨论】:

  • 谢谢托马斯;似乎defaultProps 是我最接近的了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2018-12-16
  • 1970-01-01
  • 2012-08-30
相关资源
最近更新 更多