[英]TypeScript + React <- passing props
I am trying to pass value to component props.我正在尝试将值传递给组件道具。
This is what I do:这就是我所做的:
I create interface:我创建界面:
interface CheckoutItem {
id: string,
name: string,
img: string,
unitPrice: number,
amount: number,
}
I create display component:我创建显示组件:
const CheckoutDisplay = (items: CheckoutItem[] ) => {
return (
<div>
{items.map(item => (
<p>
{item.name}
</p>
))}
</div>
)
}
I create container component:我创建容器组件:
const Checkout = (items: CheckoutItem[], setAmount: any) => {
return <CheckoutDisplay items={items} setAmount={setAmount} />;
// error here:
// Type '{ items: CheckoutItem[]; setAmount: any; }' is not assignable to type
// 'IntrinsicAttributes & CheckoutItem[]'.
// Property 'items' does not exist on type 'IntrinsicAttributes & CheckoutItem[]'.
};
const mapStateToProps = (state: any) => {
return {
items: state.items,
};
};
const mapDispatchToProps = (dispatch: AppDispatch) => {
return {
setAmount: (id: number, amount: number) => dispatch(setItemAmount(id, amount)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Checkout);
What is wrong with my code?我的代码有什么问题?
Thank you!谢谢!
Props are passed as an object to CheckoutDisplay
, so you need to destructure them.道具作为 object 传递给
CheckoutDisplay
,因此您需要对它们进行解构。
interface CheckoutDisplayProps {
items: CheckoutItem[],
setItemAmount: any,
}
const CheckoutDisplay: React.FunctionComponent<CheckoutDisplayProps> = ({ items, setItemAmount }) => {
return (
<div>
{items.map(item => (
<p>
{item.name}
</p>
))}
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.