React をページ内の一部分で使用したいと考えています。
いくつかのチュートリアルを見るとどれも要素IDの指定(ReactDOM.createRootの部分)をJSファイル内で指定していることがほとんどで、他プロジェクトで使いまわしたり id が動的に決まる場合に使いにくく感じています。
また、1ページ内で何度か使用したい場合の正しい書き方がわからず、強引に以下のようにしています。
このような用途を実現するにはどのように書くのが正しい書き方なのでしょうか?
※プログラムはブラウザ上でそのまま動作できるよう babel + webpack でトランスパイルしています。
html
1<div id="button1"></div> 2<div id="button2"></div> 3 4<script src="app.js"></script> 5<script> 6 LikeButton.init(document.getElementById('button1')); 7 LikeButton.init(document.getElementById('button2')); 8</script>
javascript
1const e = React.createElement; 2 3class LikeButton extends React.Component { 4 constructor(props) { 5 super(props); 6 this.state = { liked: false }; 7 } 8 9 render() { 10 if (this.state.liked) { 11 return 'You liked this.'; 12 } 13 14 return e( 15 'button', 16 { onClick: () => this.setState({ liked: true }) }, 17 'Like' 18 ); 19 } 20 21 // このメソッドを追加 22 static init(elem) { 23 const root = ReactDOM.createRoot(elem); 24 root.render(e(LikeButton)); 25 } 26} 27 28// グローバル変数にしている 29window.LikeButton = LikeButton;
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。