简体   繁体   English

使用Switch语句在React中期望表达

[英]Expression Expected in React using Switch Statement

I am using switch statement inside a react file .Getting Expression Expected error in first case line. 我在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>
);

If you want to inline a switch statement, you need to encase it inside an IIFE. 如果要内联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>
);

You have to use your switch statement in a function. 您必须在函数中使用switch语句。 Also, for clarity sake, you would be better off trying to keep conditional logic like that outside of your immediate component body. 另外,为清楚起见,最好将条件逻辑保持在直接组件主体之外。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM