【问题标题】:Typescript 3, React defaultProps, and passthrough propsTypescript 3、React defaultProps 和 passthrough props
【发布时间】:2019-06-03 09:45:40
【问题描述】:

我正在创建一个简单的组件,它接受一个可选的道具,但也接受任意道具传递给它的子组件,但是我不能让这个组合很好地结合在一起。我已经修改了这里的示例作为示例: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 />

只要我添加了具有任意道具的选项,我就会收到以下错误

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

我的问题是:

1) 是否有任何已知方法可以接受任意道具并使 defaultProps 起作用?

2) 这是接受任意道具的好方法吗(有更好的方法吗?

【问题讨论】:

  • 2个月后运气好吗?
  • 我想我放弃了,只是手动写出传递。有时,仅仅添加十几个额外的行比让它完美更容易。
  • 我在 typescript 3.3.3333 版本中没有看到这个问题。我也没有找到更好的方法来做到这一点。

标签: reactjs typescript typescript3.0


【解决方案1】:

如果你为内部组件定义了 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} />;
  }
}

【讨论】:

    猜你喜欢
    • 2019-02-26
    • 2017-02-19
    • 2018-05-06
    • 2017-01-24
    • 2018-09-10
    • 2018-02-02
    • 2019-06-18
    • 1970-01-01
    • 2023-01-24
    相关资源
    最近更新 更多