共计 522 个字符,预计需要花费 2 分钟才能阅读完成。
只针对函数组件
1. 第一种写法:
function App({id}) {return id==1? hello
: world
;
}
或者:
function App({id}) {return ({id==1 && "hello" || id==2 && "world" || "unknown"}
)
}
2. 如果需要条件细分,第二种写法
function App({id}) {
let content = ""
if (id==1) {content = "hello" // 如果包含 html 标签,默认会被转义}
else if (id==2) {content = "world"}
return ({content}
);
}
3. 第三种写法:
function App({id}) {return ({(()=>{if (id==1) {return "hello"}
else if (id==2) {return "world"}
})()}
);
}
switch 同理:
function App({id}) {return ({(()=>{switch(id) {
case 1:
return "hello"
case 2:
return "world"
default:
return "unknown"
}
})()}
);
}
原文地址: React JSX 使用条件语句渲染 UI 的两种写法
正文完