【问题标题】:React TypeScript: Types of property 'X' are incompatible. Type 'Y' is not assignable to type 'Z'React TypeScript:属性“X”的类型不兼容。类型“Y”不可分配给类型“Z”
【发布时间】:2019-02-20 19:23:00
【问题描述】:

我正在开发 React-TypeScript 应用程序,创建信用卡号输入组件。当用户输入信用卡号时,输入中的 FontAwesome 图标应更新为品牌形象。我收到此错误:

Types of property 'icon' are incompatible.
  Type 'string' is not assignable to type 'IconProp'

已经尝试过这个对我不起作用的解决方案:https://github.com/FortAwesome/react-fontawesome/issues/143#issuecomment-410677960

我认为这是 TypeScript 问题,错误的类型被传递给 icon prop。

这是我的 tsx 文件的简化版本,也许有帮助:

import { faCreditCard } from '@fortawesome/fontawesome-free-solid';
import { faCcMastercard, faCcVisa } from '@fortawesome/free-brands-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

const CARD_TYPES: { [index: string]: string } = {
  mastercard: 'MASTERCARD',
  visa: 'VISA',
};
const CARD_ICONS: { [index: string]: any } = {
  mastercard: faCcMastercard,
  placeholder: faCreditCard,
  visa: faCcVisa,
};

interface IProps {
  placeholder: string;
  icon: string;
}

interface IState {
  cardIcon: string;
}

export default class CardNumber extends Component<IProps,IState
> {

  constructor(props: IWmxCardNumberProps) {
   super(props);
   this.state = {
    cardIcon: CARD_ICONS.placeholder,
   };
  }

  componentDidMount() {
   this.setState({
    cardIcon: CARD_ICONS[cardType] || CARD_ICONS.placeholder
   });
  }

  onCardNumberChange(e: any) {
   this.setState({
    cardIcon: CARD_ICONS[cardType] || CARD_ICONS.placeholder
   });
  }

  public render() {
   const { cardIcon } = this.state;
   const { placeholder } = this.props;

   return (
    <Container>
     <FieldWrapper>
      <InputWrapper data-max="9999 9999 9999 9999 9999">
        {/* Error: Types of property 'icon' are incompatible. Type 'string' is not assignable to type 'IconProp' */}
        <FontAwesomeIcon icon={cardIcon} className="credit-card-icon" />
        <Input
          type="tel"
          placeholder={placeholder}
          onChange={this.onCardNumberChange}
        />
      </InputWrapper>
     </FieldWrapper>
    </Container>
   );
  }
}

那么我该如何解决这个错误呢?

【问题讨论】:

  • 你应该试试interface IState { cardIcon: IconProp; }。我相信你应该能够从@fortawesome/react-fontawesome 导入IconProp。告诉我!
  • 谢谢你解决了我的问题
  • 我必须使用以下导入:import { IconProp } from '@fortawesome/fontawesome-svg-core';.

标签: reactjs typescript font-awesome


【解决方案1】:

你需要改变这个:

interface IState {
  cardIcon: IconProp;
}

您遇到的错误是因为 icon 属性只能采用 string 的子集,即 IconProp

您可以查看here 的定义,其中包括IconName in this file 类型

【讨论】:

    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 2021-07-05
    • 2018-09-08
    • 2021-07-07
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    相关资源
    最近更新 更多