[英]Expression Expected in React using Switch Statement
我在React文件中使用switch語句。在第一種情況下獲取Expression Expected錯誤。
export default ({handle, state}) => (
<div style={styles.container} >
<h3 style={{margin: 0, marginBottom: 15}}>InputData</h3>
{items.map((item) => (
<div style={styles.lineContainer}>
switch(item.name){
case "name1": return <InputBox/>;
case "name2": return <SelectBox/>;
case "name3": return <<SelectBox/>;/>;
default: return <InputBox/>
}
</div>
))}
</div>
);
如果要內聯switch語句,則需要將其包含在IIFE中。
export default ({handle, state}) => (
<div style={styles.container}>
<h3 style={{margin: 0, marginBottom: 15}}>InputData</h3>
{items.map((item) => (
<div style={styles.lineContainer}>
{(() => {
switch(item.name) {
case "name1": return <InputBox/>;
case "name2": return <SelectBox/>;
case "name3": return <SelectBox/>;
default: return <InputBox/>
}
})()}
</div>
))}
</div>
);
您必須在函數中使用switch語句。 另外,為清楚起見,最好將條件邏輯保持在直接組件主體之外。
export default function({ handle, state }) {
function renderSwitch(item) {
switch (item.name) {
case "name1":
return <InputBox />
case "name2":
return <SelectBox />
case "name3":
return <SelectBox />
default:
return <InputBox />
}
}
return (
<div style={styles.container}>
<h3 style={{ margin: 0, marginBottom: 15 }}>InputData</h3>
{items && items.map(item => <div style={styles.lineContainer}>{renderSwitch(item)}</div>)}
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.