React-Bootstrapとは
React-Bootstrapは完全なBootstrapコンポーネントの再実装であり、Reactを使用して構築されています。bootstrap.js
またはjQueryへの依存がありません。Reactを設定し、React-Bootstrapをインストールすれば、必要なものはすべて揃います。
jQueryを使用したメソッドとイベントは、DOMに直接処理によって命令を出します。対照的に、Reactは仮想DOMを更新するために状態の更新を使用します。このように、React-BootstrapはBootstrapの機能をReactの仮想DOMに組み込むことで、より信頼性の高いソリューションを提供します。以下に、React-BootstrapコンポーネントがBootstrapとどのように異なるかを示す例をいくつか示します。
シンプルなReactコンポーネント
BootstrapコンポーネントのCSSと詳細は、かなり主観的で長くなっています。React-Bootstrapは、元のBootstrapをReactスタイルのコンポーネントに凝縮することでこれを簡素化しています。
Bootstrap
import * as React from 'react';
function Example() {
return (
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<strong>Oh snap! You got an error!</strong>
<p>Change this and that and try again.</p>
<button
type="button"
class="close"
data-dismiss="alert"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
);
}
React-Bootstrap
import * as React from 'react';
import Alert from 'react-bootstrap/Alert';
function Example() {
return (
<Alert dismissible variant="danger">
<Alert.Heading>Oh snap! You got an error!</Alert.Heading>
<p>Change this and that and try again.</p>
</Alert>
);
}
状態を持つBootstrap
React-BootstrapはReactのJavaScriptで構築されているため、状態はReact-Bootstrapコンポーネント内にpropsとして渡すことができます。また、更新はDOMの状態を直接操作するのではなく、Reactの状態を使用して実行されるため、状態を管理しやすくなります。これにより、より複雑なコンポーネントを作成する際に大きな柔軟性も生まれます。
React-bootstrap
結果
ロード中...
ライブエディター
Bootstrap
<div class="alert alert-success alert-dismissible fade show firstCollapsible" role="alert">
<strong>How's it going?!</strong>
<p>
Duis mollis, est non commodo luctus, nisi erat porttitor ligula,
eget lacinia odio sem nec elit. Cras mattis consectetur purus sit
amet fermentum.
</p>
<hr/>
<div class="d-flex justify-content-end">
<button type="button" class="btn btn-outline-success">Close me ya'll!</button>
</div>
</div>
<div class="d-flex justify-content-start alert fade show">
<button type="button" class="btn btn-primary d-none secondCollapsible">Show Alert</button>
</div>
$('.btn-outline-success').on('click', function(e) {
$('.firstCollapsible').addClass('d-none');
$('.secondCollapsible').removeClass('d-none');
})
$('.btn-primary').on('click', function(e) {
$('.firstCollapsible').removeClass('d-none');
$('.secondCollapsible').addClass('d-none');
})