この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - JavaScript コーディング問題
140. Virtual DOM III - Functional Component
解法:
Functional Componentをサポートするには、createElement()
に少し変更を加える必要があります。
- もし要素がFunction Componentなら、呼び出し、その戻り値をcreateElementの引数とする。
- それ以外は、通常通りcreateElementを呼び出す。
また、render()
にも少し変更を追加する必要があります。
- もし
MyElement
がFunction Componentなら、呼び出して戻り値を再びrender()
に渡す。 - さもなくば、新しい実際のDOMノードを作成し、子要素を再帰的にすべて処理し、DOMノードに追加する。
実際のコードは以下の通りです:
function createElement(MyElement, props, ...children) { if (typeof MyElement === 'function') { return MyElement(props) } const element = document.createElement(MyElement) for (let [key, value] of Object.entries(props)) { if (key === 'className') { element.setAttribute('class', value) } else { element.setAttribute(key, value) } } children.flat().forEach(child => { if (typeof child === 'string') { element.appendChild(document.createTextNode(child)) } else { element.appendChild(createElement(child)) } }) return element}function render(MyElement, container) { while (container.firstChild) { container.removeChild(container.firstChild) } const element = createElement(MyElement) if (typeof element === 'string') { container.appendChild(document.createTextNode(element)) } else { container.appendChild(element) }}
これで、Functional Componentも含めて正しく結果が表示されます。