簡體   English   中英

如何修改給定 JSX.Element 屬性的子級?

[英]How to modify children of a given JSX.Element property?

我有以下組件:

import React, { ReactElement } from 'react'

interface Props {
  icon: JSX.Element; // should accept only svg
  fill?: string;
  stroke?: string;
}

export default function AppIcon(props: Props): ReactElement {
  // TODO:
  // Replace: svg *[fill] = props.fill
  // Replace: svg *[stroke] = props.stroke 
}

如您所見,該組件接受一個 JSX.Element 圖標(不知道如何將其限制為僅 SVG)。

之后,它應該在icon樹中查找具有fillstroke屬性的子項並相應地替換。 意思是,如果有一個帶有fill的路徑,它將用給定的 fill 替換它。 如果路徑沒有fill ,則不會添加它。

我怎樣才能實現這種行為?

我想我已經設法得到你想要的工作:

import React, { ReactElement } from "react";
import "./AppIcon.css";

interface Props {
    children: JSX.Element;
    fill?: string;
    stroke?: string;
}

export default function AppIcon(props: Props): ReactElement {
    return (
        // @ts-ignore
        <div className="AppIcon" style={{ "--fill": props.fill, "--stroke": props.stroke }}>
            {props.children}
        </div>
    );
}

AppIcon.css

.AppIcon > svg * {
    fill: var(--fill);
    stroke: var(--stroke);
}

使用組件:

...
<AppIcon fill="blue" stroke="yellow">
    <svg>
        <circle cx="50" cy="50" r="40" strokeWidth="3" />
    </svg>
</AppIcon>
...

解釋:

  • 首先,道具界面上的icon屬性應該是children React 將使用組件的任何子項填充該屬性。 據我所知,不幸的是,沒有辦法將其限制為某個標簽名稱。

  • 然后它在 div 標簽下呈現孩子。 在這里,我給那個div標簽一個 className 以便稍后識別,我給這個 div 一個帶有兩個css 自定義屬性的樣式,其中它們的值與道具提供的填充和描邊相匹配。 (TypeScript 不喜歡這樣,因為它們沒有定義,所以我們有// @ts-ignore

  • 這些屬性可以被 div 元素的任何后代/子元素訪問。 因此,在相鄰的樣式表中,我們將 svg 中的元素設置為使用樣式表中通過var()關鍵字設置的變量。

代碼沙盒中的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM