我將所有 SVC 都作為反應組件,如下所示,我希望選擇將顏色屬性作為道具傳遞以覆寫組件的默認顏色。但是,添加一個 props 屬性就可以了,它給我留下了一個丑陋的物件,我必須在父組件中定義它。我該如何解決?
SVG
import React, { SVGAttributes } from 'react'
interface WalletProps {
props?: SVGAttributes<any>
}
const Wallet: React.FC<WalletProps> = ({ ...props }) => {
return (
<svg
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
{...props}
>
...
</svg>
)
}
export default Wallet
所以要添加顏色,我最終得到了這個:<Wallet props={{ color: 'red' }} />但我想要<Wallet color="red" />. 理想情況下,我希望它適用于 SVG 元素使用的高度、寬度、類名和所有其他屬性。
非常感謝
uj5u.com熱心網友回復:
您可以宣告WalletProps為React.SVGProps<SVGSVGElement>,以便它包含 SVG 元素的所有屬性。然后不再需要解構props:
type WalletProps = React.SVGProps<SVGSVGElement>;
const Wallet: React.FC<WalletProps> = (props) => {
return (
<svg
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
{...props}
>
...
</svg>
)
}
如果您有其他道具要合并到其中,例如fooand bar,則需要創建一個聯合型別:
type WalletProps = React.SVGProps<SVGSVGElement> & { foo: FooType, bar: BarType };
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414462.html
標籤:
