本文最后更新于421 天前,其中的信息可能已经过时,如有错误请发送邮件到1986413837@qq.com
解题目标 完善JSX函数 实现下列目标




JSX 函数需实现以下目标:
- 完成元素的 DOM 节点转换,即只转换
config中的children。 - 完成元素的属性转换,其中元素样式如果是小驼峰写法需要转换成
-连接,如fontSize需转换成font-size。js/index.js文件中的isUpperCase函数功能为判断字符是否为大写。注意:样式必须转换为行内样式 - 完成元素事件正确绑定与触发
主要还是考察对象和数组的操作 以及 对于Dom元素的操作问题
直接粘贴源代码
const jsx = (type, config) => {
/* TODO: 待补充代码 */
//要求返回的是一个节点 而不是字符串!!!
//所以要用JS创建一个新的Dom元素
const node = document.createElement(type)
//1
//只有一个字符串时
if(typeof config.children == 'string'){
node.innerHTML = config.children
}
else {
config.children.forEach(ele => {
if(typeof ele =='string'){
node.innerHTML+= ele
}
else {
//添加子节点即可
node.appendChild(ele)
}
})
}
//2
if(config.style){
let style=''
//获得style对象的键值
for(let key of Object.keys(config.style)){
let keys = key.split('')
//'f' 'o' 'n' 't' 'S' 'i' 'z' 'e'
//用map处理数组 需要给一个新的地址
let newKeys=keys.map(c=>{
if(isUpperCase(c)){
c='-'+ c.toLowerCase()
return c
}
else {
return c
}
}).join('')
style +=`${newKeys}:${config.style[key]};`
}
//setAttribute设置属性
node.setAttribute('style',style)
}
if(config.id){
node.setAttribute('id',config.id)
}
//3
if(config.onclick){
node.addEventListener('click',config.onclick)
}
return node
};
哈喽