140. Virtual DOM III - Functional Component

JavaScript Meta

容易  -通过 / -执行

该问题紧接118. Virtual DOM II - createElement.

在问题118中,你需要实现支持原生HTML元素的createElement()render()

该问题中,你需要扩展到Functional Component

Functional Component是如下函数:

  1. 接受 单一 object 参数 -props,其中含有 childrenclassName 以及其他属性。
  2. 调用createElement()并返回 MyElement。

假设我们有如下的Function Component - Title

const h = createElementconst Title = ({children, ...res}) => h('h1', res, ...children)

这意味着可以和原生HTML元素一样直接使用createElementrender()

h(Title, {}, 'This is a title')h(Title, {className: 'class1'}, 'This is a title')

请根据需要调整问题118中你所完成的createElement()render(),使得问题118中的sample也可以按照如下的方式书写。

const Link =   ({children, ...res}) => h('a', res, ...children)const Name =   ({children, ...res}) => h('b', res, ...children)const Button =   ({children, ...res}) => h('button', res, ...children)const Paragraph =   ({children, ...res}) => h('p', res, ...children)const Container =    ({children, ...res}) => h('div', res, ...children)h(  Container,  {},  h(Title, {}, ' this is '),  h(    Paragraph,    { className: 'paragraph' },    ' a ',    h(Button, {}, ' button '),    ' from ',    h(      Link,       { href: 'https://bfe.dev' },       h(Name, {}, 'BFE'),       '.dev')  ))

始终思考更好的解决办法