我有這個組件,右邊只是一個標題和一個圖示,這個組件的容器可以是一個按鈕,一個錨元素,也可以是一個來自react-router-dom.

我能夠像這樣動態創建容器:
import { Link } from "react-router-dom";
// ....
type Props = {
as: "button" | "a" | "Link";
title: string;
icon: string;
};
const ActionItem: React.FC<Props> = ({ as, title, icon }: Props) => {
const Container = styled(as === "Link" ? Link : as)`
display: flex;
// ...
`;
return (
<Container>
{title}
<div style={{ flex: 1 }} />
{icon}
</Container>
);
};
但現在我想要做到的是有活力的道具取決于as支柱,因此,舉例來說,如果as道具等于Link顯示像鏈接組件的所有道具to,replace等等。或者,如果as等于a,顯示了錨元素像所有的道具href,target等等。
<ActionItem
as="Link"
to="/profile"
...
/>
我試過這個但它沒有用,主要是因為在示例中他們使用原生 HTML 元素,我需要使用這些(按鈕和錨元素)加上 Link 組件。
我不知道我想要找到的東西是否可行,或者它是否是另一種可能的解決方案?
順便說一句,這是一個帶有代碼的代碼沙箱
編輯:這是代碼的沙箱,它應該正常作業
uj5u.com熱心網友回復:
您應該使用所謂的判別聯合(或判別聯合)。讓我們使用as道具作為鑒別器。
你已經有了
type Props = {
as: "button" | "a" | "link"
}
打破那個
type Props =
{ as: "button" } |
{ as: "a" } |
{ as: "Link" }
現在簡單地將你期望的屬性添加到聯合的每個部分,Typescript 可以推斷出其他可能的屬性,給定鑒別器 prop as:
type Props =
{ as: "button" } & ButtonProps |
{ as: "a" } & AProps |
{ as: "Link" } & LinkProps
完畢!
順便說一句,我使用了你需要的補充道具的名字,你必須查找你想要與你自己的鑒別器道具相交的型別的名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350691.html
