###前提・実現したいこと
Riot.jsにて、動的にカスタムタグをマウントしたい。
###発生している問題・エラーメッセージ
カスタムタグのマウント時の初期化で、DOM操作(getElementByIdなど)したものの、アクセスしたい要素にアクセスできず、要素のプロパティ参照時にnullが取得される。
エラーメッセージ Uncaught TypeError: Cannot read property 'プロパティ名' of null(…)
###該当のソースコード
[マウント元] <my-tag> <h3>マウント元タグ</h3> <div> <button type="button" onclick={ btnClick }>トリガー</button> <mount-tag each={ item in items } item={ item }/></div> </div> <script> var items var cnt /*** 初回マウント時実施 ***/ this.on('mount', function(){ this.init() }) /*** 初期化 ***/ init(){ items = [] cnt = 0 } /*** ボタンクリック時 ***/ btnClick(e){ cnt = cnt + 1 var item = { 'id' : cnt } items.push(item) riot.compile(function(){ riot.mount('mount-tag') }) this.update() } </script> </my-tag> [マウント先] <mount-tag> <h3>マウント先タグ</h3> <div id={ opts.item.id } data-target="10"> 取得したいdiv </div> <script> var getDiv /*** 初回マウント時実施 ***/ this.on('mount', function(){ this.init() }) /*** 初期化 ***/ init(){ getDiv = document.getElementById(opts.item.id) // getElementByIdで要素にアクセスできず、nullが返される。 console.log(opts.item) // optsによる値の受け渡しは行われている。 console.log(getDiv.dataset.target) // ここでエラー } </script> </mount-tag> div each={ item in items } で、itemsにpushされて値が増えるたびに、mount-tagを動的にマウントしたい
###試したこと
上記のとおり。
また、これら2つのタグは、index.htmlで読み込み済みであり、コンパイルもしている。
[index.html] <!DOCTYPE html> <html> <head> (略) </head> <body> <script type="riot/tag" src="tag/my-tag.html"></script> <script type="riot/tag" src="tag/mount-tag.html"></script> </body> </html> [index.js] init(){ riot.compile(function() { riot.route.base('/BaseURL/') riot.route.start(true) riot.mount('*') }) }
###補足情報(言語/FW/ツール等のバージョンなど)
バージョン
riot: 2.6.4
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。