簡體   English   中英

簡化第 3 方組件道具?

[英]Simplify 3rd party component prop?

我正在使用 React 組件markdown-to-jsx將 markdown 字符串轉換為 HTML。它能夠獲取我創建的自定義組件並使用它們來呈現自定義標簽。 然而,這樣做的支持非常冗長,有點煩人,我希望簡化它,但很難實現。

示例:我想向我的 markdown 渲染添加一個組件 Dice。 這非常有效,但是哇,需要大量輸入:

import Markdown from 'markdown-to-jsx';
import Dice from './Dice';
...
<Markdown options={{ overrides: { Dice: { component: Dice } } }}>
  {markdownContent}
</Markdown>

哇,如果我想添加幾個組件怎么辦? 丑陋。 所以,我有了一個想法:編寫一個使用markdown-to-jsx的組件並簡化 props:

import Markdown from 'markdown-to-jsx';
(other imports)
...

// Take the original component and run a map to create that ugly verbose code.
function Md({ components, children }) {
  const comps = components.map((c) => ({ [c.name]: { component: c } }));
  return <Markdown options={{ overrides: { comps } }}>{children}</Markdown>;
}

...
<Md components={[Dice, Attack, Foo]}>
  {markdownContent}
</Md>

很酷,對吧? 不,它不起作用。 我不斷收到這些錯誤:

  • <Dice /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
  • Warning: The tag <Dice> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter

為什么丑陋的版本可以,而我的不行???

你很接近, components.map返回一個數組但overrides需要 object,在你的情況下你可以使用component.reduce將值聚合到 object 中。

const comps = components.reduce((accumulator, c) => { 
    accumulator[c.name] = {component: c};
    
    return accumulator;
}, {});

它還會稍微影響 return 語句:

return <Markdown options={{ overrides: comps }}>{children}</Markdown>;

暫無
暫無

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

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