Skip to main content

カスタムコンポーネントに渡された値

カスタムコンポーネントで、markdown から呼び出したときの情報の取得についてのまとめ。

サマリ

#取得元Markdown上の記載
HTML レンダリング結果
1なにも取得しない<SampleTagGetNothing/>
これは引数を受け取らないサンプルです
2属性から取得する<SampleTagGetAttrs attr1="あー" attr2="あいう" />
attr1 は [ あー ]で、attr2 は [ あいう ] です
3タグ内から取得する<SampleTagGetChildren>あああ</SampleTagGetChildren>
タグ内の文字は [ あああ ] です

1. なにも取得しない

コード

md
import SampleTagGetNothing from '@site/src/components/SampleTagGetNothing';

<SampleTagGetNothing/>
src/components/SampleTagGetNothing.tsx
import React from 'react';

const SampleTagGetNothing: React.FC = () => {
return <span className="sample-highlight">これは引数を受け取らないサンプルです</span>;
};

export default SampleTagGetNothing;

このように表示される

これは引数を受け取らないサンプルです

2. 属性(attribute)から取得する

コード

md
import SampleTagGetAttrs from '@site/src/components/SampleTagGetAttrs';

<SampleTagGetAttrs attr1="あー" attr2="あいう" />
src/components/SampleTagGetAttrs.tsx
import React from 'react';

interface SampleTagGetAttrsProps {
attr1: string;
attr2: string;
}

const SampleTagGetAttrs: React.FC<SampleTagGetAttrsProps> = ({ attr1, attr2 }) => {
return (
<span className="sample-highlight">
attr1 は [ {attr1} ]で、attr2 は [ {attr2} ] です
</span>
);
};

export default SampleTagGetAttrs;

このように表示される

attr1 は [ あー ]で、attr2 は [ あいう ] です

3. タグで囲まれた部分(children) から取得する

コード

md
import SampleTagGetChildren from '@site/src/components/SampleTagGetChildren';

<SampleTagGetChildren>タグに挟まれた部分。`markdown` も受け付けるようだ</SampleTagGetChildren>
src/components/SampleTagGetChildren.tsx
import React from 'react';

interface SampleTagGetChildrenProps {
children: React.ReactNode;
}

const SampleTagGetChildren: React.FC<SampleTagGetChildrenProps> = ({ children }) => {
return (
<span className="sample-highlight">タグ内の文字は [ {children} ] です</span>
);
};

export default SampleTagGetChildren;

このように表示される

タグ内の文字は [ タグに挟まれた部分。markdown も受け付けるようだ ] です