属性不存在于类型 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }> ...'

dig*_*fee 6 typescript reactjs material-ui

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

属性 'openToYearSelection' 不存在于类型 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }> ...'。

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

在 TypeScript 和 React 中使用 Material-UI 的正确方法是什么?

dig*_*fee 1

我通过向文件中的命名空间添加缺少的属性解决了这个问题 node_modules/@types/material-ui/index.d.ts。这对我有用。我认为这不是一个好的解决方案,我想知道是否有更好的方法。

namespace DatePicker {
    export interface DatePickerProps {
        defaultDate?: Date;
        disableYearSelection?: boolean;
        ..
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,这不是一个好的解决方案。我想补充一点,这甚至不是一个解决方案。您无法编辑 node_modules 中的任何内容并期望可重现的构建/行为,因为每个“npm install”都会擦除它。如果您需要自定义道具,可以使用扩展运算符。打字稿不会检查这个`&lt;Something {...{key: 'value'}} /&gt;` (3认同)