React TypeScript:属性“X”的类型不兼容。类型'Y'不能分配给'Z'类型

问题描述 投票:2回答:1

我正在研究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>
   );
  }
}

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

reactjs typescript font-awesome
1个回答
0
投票

你需要改变这个:

interface IState {
  cardIcon: IconProp;
}

你得到的错误是因为icon道具只能采取stringIconProp子集。

你可以看一下here的定义,其中包括IconName in this file

© www.soinside.com 2019 - 2024. All rights reserved.