【问题标题】:Property does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }> ...'类型 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; 上不存在属性}> ...'
【发布时间】:2018-10-14 00:54:45
【问题描述】:

我正在尝试将 React 与 TypeScript 和 Material-UI 的组件一起使用。不幸的是,我遇到了这样的错误:

类型上不存在属性“openToYearSelection” 'IntrinsicAttributes & IntrinsicClassAttributes & 只读 ...'。

import * as React from 'react';
import DatePicker from 'material-ui/DatePicker';

interface IState {
  birthday: any,
}

export default class SampleForm extends React.Component<IProps, IState> {
  constructor(props: any) {
    super(props);

    const { record = {} } = this.props;

    this.state = {
      birthday: record.birthday || null,
    };
  }

  public birthdayPicker() {
    const { birthday } = this.state;

    return (
      <DatePicker
        defaultDate={birthday}
        hintText="Birthday"
        openToYearSelection={true}
      />
    );
  }

  public render() {
    return (
      <form style={styles.root}>
        {this.header()}
        {this.firstName()}
        {this.lastName()}
        {this.birthdayPicker()}
        {this.phoneNumber()}
        {this.actionButtons()}
      </form>
    )
  }
}

将 Material-UI 与 TypeScript 和 React 结合使用的正确方法是什么?

【问题讨论】:

  • 您使用的是@types/material-ui 包吗?您的 material-ui 版本是 0.x 版本还是 v1-beta 版本?
  • 嗨@CRice,我正在使用@types/material-ui 并将material-ui 设置为“^0.20.0”。我尝试使用属性更新@types/material-ui/index.d.ts 文件(请在下面查看我的答案)。但是,我想这是一种硬编码,不是合适的解决方案。
  • 我认为该解决方案很好,我对许多其他软件包都做了同样的事情。 @types/material-ui 包肯定缺少一些属性,我认为您不能从外部扩充该接口。 FWIW,当 material-ui v1 下降时,类型将直接包含在 repo 中(因此不需要@types),并希望保持最新。
  • @CRice,听起来不错!感谢您的帮助。
  • 尝试在出错的行上方添加// @ts-expect-error

标签: reactjs typescript material-ui


【解决方案1】:

如果它是第三方库,您可以在出错的行上方添加它,它会忽略错误并让您构建:

// @ts-expect-error

【讨论】:

    【解决方案2】:

    我已通过在 node_modules/@types/material-ui/index.d.ts 文件。它对我有用。我认为这不是一个好的解决方案,我想知道是否有更好的方法。

    namespace DatePicker {
        export interface DatePickerProps {
            defaultDate?: Date;
            disableYearSelection?: boolean;
            ..
    

    【讨论】:

    • 你说得对,这不是一个好的解决方案。我要补充一点,它甚至不是解决方案。您不能编辑 node_modules 中的任何内容并期望可重现的构建/行为,因为每个npm install 都会擦除它。如果您需要自定义道具,可以使用扩展运算符。打字稿不检查这个&lt;Something {...{key: 'value'}} /&gt;
    • @Simon 即使您的建议也不起作用。我也试着用这种方式传递道具。
    猜你喜欢
    • 2020-09-03
    • 2020-11-07
    • 2020-01-24
    • 2021-07-12
    • 2021-08-20
    • 1970-01-01
    • 2019-12-11
    • 2020-11-29
    • 2018-10-11
    相关资源
    最近更新 更多