我正在研究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;
}
你得到的错误是因为icon
道具只能采取string
的IconProp
子集。
你可以看一下here的定义,其中包括IconName
in this file