首页 > 解决方案 > 使用 Switch 语句在 React 中预期的表达式

问题描述

我在反应文件中使用 switch 语句。在第一个案例行中获取表达式预期错误。

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>
);

标签: javascriptreactjsreact-native

解决方案


如果要内联 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>
);

推荐阅读