gpt4 book ai didi

reactjs - React TypeScript : Types of property 'X' are incompatible. 类型 'Y' 不可分配给类型 'Z'

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:28 25 4
gpt4 key购买 nike

我正在开发 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 Prop 只能采用 string 的子集,即 IconProp

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

关于reactjs - React TypeScript : Types of property 'X' are incompatible. 类型 'Y' 不可分配给类型 'Z',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com