140. Virtual DOM III - Functional Component
分享给更多人
容易 -通过 / -执行
在问题118中,你需要实现支持原生HTML元素的createElement()
和 render()
。
该问题中,你需要扩展到Functional Component。
Functional Component是如下函数:
- 接受 单一 object 参数 -
props
,其中含有children
、className
以及其他属性。 - 调用
createElement()
并返回 MyElement。
假设我们有如下的Function Component - Title
const h = createElementconst Title = ({children, ...res}) => h('h1', res, ...children)
这意味着可以和原生HTML元素一样直接使用createElement
和 render()
。
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') ))