Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9004

classNameを上書きできるReactコンポーネントを作る方法

$
0
0

classNameにクラス名を割り当ててスタイリングしたコンポーネントを実装すると、
単純に実装しただけではコンポーネントの呼び出し時にclassName属性を新たに追加(注)した際に元々のスタイリングが全て消えてしまう。

注: これをやるには元々のHTMLタグが持つpropsを受け継がせる必要がある

解決策は、classNameの指定部分にクラス名を挿入可能にすればよい。

App.css
.text-red{color:red;}.text-bold{font-weight:bold;}.text-big{font-size:24px;}
App.tsx
import"./App.css";importclassnamesfrom"classnames";typeRedTextProps={children:React.ReactNode;className?:string};functionRedText({children,className}:RedTextProps){return<pclassName={classnames("text-red",className)}>{children}</p>;
}functionApp(){return(<div>{/* 赤色 */}<RedText>Loremipsumdolorsitamet.</RedText>
{/* 赤色、太字 */}<RedTextclassName="text-bold">Loremipsumdolorsitamet.</RedText>
{/* 赤色、太字、サイズ大 */}<RedTextclassName={classnames("text-bold","text-big")}>Loremipsumdolorsitamet.</RedText>
</div>
);}exportdefaultApp;

Viewing all articles
Browse latest Browse all 9004

Trending Articles