この解答例はChatGPTによって生成されています,正しいかは自己判断で。
BFE.devでのAI解答例 - JavaScript コーディング問題
150. Virtual DOM V - JSX 2
function flattenChildren(children) {
return [].concat(...children.map(child => {
if(typeof child === 'string') {
return { type: 'TEXT_ELEMENT', props: {nodeValue: child} }
} else if(typeof child.type === 'string') {
return { type: child.type.toUpperCase(), props: {...child.props, children: flattenChildren(child.props.children)} }
} else if(typeof child.type === 'function') {
return flattenChildren(child.type(child.props))
}
}))
}
function createElement(type, props, ...children) {
return {
type: type.toUpperCase(),
props: { ...props, children: flattenChildren(children) }
}
}
function render(target, parent) {
parent.appendChild(target)
}
const B = ({ children }) => createElement('strong', {}, ...children)
const Greeting = ({ name }) => <p>Hello, <B>{name}</B></p>
render(<Greeting name="BFE.dev"/>, document.getElementById('root'))