reactjs - Typescript 3、React defaultProps 和 passthrough Prop

标签 reactjs typescript typescript3.0

我正在创建一个简单的组件,它接受一个可选的 prop,但也接受任意的 props 传递给它的子组件,但是我无法让这种组合很好地协同工作。我已经修改了此处的示例作为示例:Typescript3 Release Notes

import React from 'react';

export interface Props {
  name: string;
  [id: string]: any; // <-- Added to allow acceptance of arbitrary props
}

export class Greet extends React.Component<Props> {
  render() {
    const { name, ...divProps } = this.props;
    return <div {...divProps}>Hello {name.toUpperCase()}!</div>;
  }

  static defaultProps = { name: 'world' };
}

用法:

<Greet />

一旦我添加了具有任意 Prop 的选项,我就收到以下错误

Property 'name' is missing in type '{}' but required in type 'Readonly<Props>'.

我的问题是:

1) 是否有任何已知的方法来接受任意 props 并使 defaultProps 起作用?

2) 这是接受任意 props 的好方法吗?

最佳答案

如果您为内部组件定义了 props,您可以将它们交叉 (&) 在一起,这样您的所有 props 就会具有类型安全性。

type Props = {
  name: string;
}

type InnerCompProps = {
  color: string,
}

const InnerComp = (props: InnerCompProps) => (<div> the color is { props.color} </div>);

export class Greet extends React.Component<Props & InnerCompProps> {
  static defaultProps = { name: 'world' };

  render() {
    const { name, ...rest } = this.props;
    return <InnerComp {...rest} />;
  }
}

关于reactjs - Typescript 3、React defaultProps 和 passthrough Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54096222/

相关文章:

javascript - 模块构建失败 : Error: write EPIPE (or make processCssUrls:false) in css imports Laravel Mix

reactjs - react 谷歌地图getBounds

reactjs - 从 React Native 登录 Google 时出现 TypeError - Expo

reactjs - 通过排序/分页向表格添加骨架效果

typescript - 如何清理 typescript 缓存?

reactjs - typescript 3 : property is missing in type

reactjs - 在 TypeScript 项目之间共享代码(使用 React)?

javascript - 使用 fetch 发布 JSON 数据

typescript - 使用 Prisma + Next-Auth 通过 EmailProvider 登录时获取 'CreateVerificationTokenError'

TypeScript tsc > 消息重定向