我在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>
);
答案 0 :(得分:4)
如果要内联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>
);
答案 1 :(得分:1)
您必须在函数中使用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>
)
}