我有一个CardsList
组件,该组件呈现Card
组件的列表。 Card
组件将呈现一个不同的CardElements
列表。
在其中一个组件上,我传递了卡片模型的当前实例以呈现一些数据。
我想停止传递card属性,而是使用React.Context
API。
const card = useContext(CurrentCardContext)
我该怎么做?以及如何获取每张卡的正确上下文?
我尝试创建一个全局CurrentCardContext并将其作为提供程序传递到Card中。但是,这不起作用,因为当我尝试使用上下文时会得到空卡:
export const CurrentCardContext: Context<ICard> = React.createContext<ICard>(null);
然后在CardsList中:
<div key={i} data-card-list-item={i}>
<CurrentCardContext.Provider value={card}>
<Card card={card}/>
</CurrentCardContext>
</div>
我有一个与此相似的CardsList组件:
export const CardsList: FunctionComponent<ICardsListProps> =
({ cardsReferences }: ICardsListProps): JSX.Element =>
(
<div className="cards-list" data-cards-list="true">
{map(cards, (card: ICard, i: number) =>
(
<div key={i} data-card-list-item={i}>
<Card card={card}/>
</div>
))}
</div>
);
卡包含基于参数的不同类型的元素到不同类型的元素。例如:
export const Card: FunctionComponent<ICardProps> =
({card, onSelect, className}: ICardProps): JSX.Element => {
const elements = cardsService.parseCardElements(card);
return (
<div className={classnames('ui basic segment elevated card card-selected', className)} data-card-id={card.cardId}>
<div className="content card-body">
{map(elements, (element: CardContent, i: number) => (<CardElement key={i} index={i} element={element} card={card}/>))}
</div>
</div>
);
};
CardElement是这样的:
export const CardElement: FunctionComponent<ICardElementProps> =
({ element, index, card }: ICardElementProps): JSX.Element => {
switch (element.type) {
case CardContentTypes.markdown:
return <MarkdownElementContainer content={element as IMarkdownCardContent} index={index}/>;
case CardContentTypes.imageBackground:
return <ImageBackgroundElement body={element.body as IImageBackgroundCardBody} index={index}/>;
case CardContentTypes.link:
return <LinkElement content={element as ILinkCardContent} index={index} card={card}/>;
case CardContentTypes.imageTextLink:
return <LinkElement content={element as ILinkCardContent} index={index}/>;
case CardContentTypes.splitMedia:
return <SplitMediaElementContainer content={element as ISplitMediaCardContent} index={index}/>;
case CardContentTypes.list:
return (<ListElement content={element as IAccordionElements} index={index} />);
default:
return null;
}
};
我想停止在linkElement的此嵌套项目列表中传递card属性 因此LinkElement将是:
<LinkElement content={element as ILinkCardContent} index={index} />;
我希望在内部组件中获取当前的卡片上下文,但我会得到null。