preact-custom-elementの属性にobjectを渡
す
HTMLタグとして使うときは無理
HTML要素の属性には文字列しか渡せないので当然といえば当然なんだけどtakker.icon
JSON.parse()を使うのが対策になるかもしれないが、複雑なobjectを渡す場合には使えなさそう
sample
code:js
import('/api/code/programming-notes/preact-custom-elementの属性にobjectを渡/sample1.js')
.then(({mount}) => mount(scrapbox.Page.lines.slice(0, 10)));
code:sample1.js
import {html, render} from '../htm@3.0.4%2Fpreact/script.js';
import register from '../preact-custom-element@4.2.1/script.js';
const Viewer = ({data}) => html<pre><code>${JSON.stringify(data, null, 2)}</code></pre>;
register(Viewer, 'x-userscript-viewer', 'data', {shadow: true}); export function mount(data) {
const app = document.createElement('div');
app.dataset.userscriptName = 'preact-custom-element-test';
document.getElementById('editor').append(app);
render(html<x-userscript-viewer data="${data}"/>, app);
}
HTMLタグを文字列で書かなければならず、バグの温床になるのが欠点
Custom Elementにしたものを、更にComponentでwrapすれば使いやすくなりそう
code:js
import('/api/code/programming-notes/preact-custom-elementの属性にobjectを渡/sample2.js')
.then(({mount}) => mount(scrapbox.Page.lines.slice(0, 10), 'foo', 'bar')); code:sample2.js
import {html, render} from '../htm@3.0.4%2Fpreact/script.js';
import register from '../preact-custom-element@4.2.1/script.js';
const Viewer_ = ({props}) => html`
${props.messages?.map?.(message => html<p>${message}</p>)}
${props.contents && html<pre><code>${JSON.stringify(props.contents, null, 2)}</code></pre>}
`;
register(Viewer_, 'x-userscript-viewer', 'props', {shadow: true}); const Viewer = ({children, ...props}) => html<x-userscript-viewer props=${props} />;
export function mount(data, messages) {
const app = document.createElement('div');
app.dataset.userscriptName = 'preact-custom-element-test';
document.getElementById('editor').append(app);
render(html<${Viewer} contents="${data}" messages="${messages}" />, app);
}
複数の属性を指定すると動かなくなる
何故だ?
理由は不明だが、回避策はある
一つの属性に全てのpropertyを詰め込んでしまえばいい