我有一个React组件,在组件的渲染方法中,我有这样的东西:

render() {
    return (
        <div>
            <div>
                // removed for brevity
            </div>

           { switch(...) {} }

            <div>
                // removed for brevity
            </div>
        </div>
    );
}

Now the point is that I have two div elements, one at the top and one at the bottom, that are fixed. In the middle I want to have a switch statement, and according to a value in my state I want to render a different component. So basically, I want the two div elements to be fixed always, and just in the middle to render a different component each time. I'm using this to implement a multi-step payment procedure). Though, as is the code currently it doesn't work, as it gives me an error saying that switch is unexpected. Any ideas how to achieve what I want?


当前回答

这是因为switch语句是一个语句,但这里javascript需要一个表达式。

虽然,不建议在呈现方法中使用switch语句,但你可以使用自调用函数来实现这一点:

render() {
    // Don't forget to return a value in a switch statement
    return (
        <div>
            {(() => {
                switch(...) {}
            })()}
        </div>
    );
}

其他回答

这是另一种方法。

render() {
   return {this[`renderStep${this.state.step}`]()}

renderStep0() { return 'step 0' }
renderStep1() { return 'step 1' }

你可以这样做。

 <div>
          { object.map((item, index) => this.getComponent(item, index)) }
 </div>

getComponent(item, index) {
    switch (item.type) {
      case '1':
        return <Comp1/>
      case '2':
        return <Comp2/>
      case '3':
        return <Comp3 />
    }
  }

我正在使用这个帮助器,它允许我在JSX中有开关语句

// in helpers folder const switchTrue = (object) => { const { default: defaultValue, ...rest } = object; const obj = { default: defaultValue, ...rest }; const result = Object.keys(obj).reduce((acc, cur) => { return { ...acc, [cur === 'default' ? 'true' : cur]: obj[cur], }; }, {}); return result['true']; }; const Sample = () => { const isDataLoading = false; return ( <div> { switchTrue({ [`${isDataLoading}`]: <div>Loading</div>, [`${!isDataLoading}`]: <div>Data Ready</div>, default: <div>Default</div>, }) } </div> ) } ReactDOM.render( <Sample/>, document.getElementById("react") ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="react"></div>

试试这个,它也更干净:在一个函数中获得渲染的开关,并调用它传递你想要的参数。例如:

renderSwitch(param) {
  switch(param) {
    case 'foo':
      return 'bar';
    default:
      return 'foo';
  }
}

render() {
  return (
    <div>
      <div>
          // removed for brevity
      </div>
      {this.renderSwitch(param)}
      <div>
          // removed for brevity
      </div>
    </div>
  );
}

这个答案专门用来解决@tonyfat提出的“重复”问题,关于如何使用条件表达式来处理相同的任务。


Avoiding statements here seems like more trouble than it's worth, but this script does the job as the snippet demonstrates:

// Runs tests let id = 0, flag = 0; renderByFlag(id, flag); // jobId out of range id = 1; // jobId in range while(++flag < 5){ // active flag ranges from 1 to 4 renderByFlag(id, flag); } // Defines a function that chooses what to render based on two provided values function renderByFlag(jobId, activeFlag){ jobId === 1 ? ( activeFlag === 1 ? render("A (flag = 1)") : activeFlag === 2 ? render("B (flag = 2)") : activeFlag === 3 ? render("C (flag = 3)") : pass(`flag ${activeFlag} out of range`) ) : pass(`jobId ${jobId} out of range`) } // Defines logging functions for demo purposes function render(val){ console.log(`Rendering ${val}`); } function pass(reason){ console.log(`Doing nothing (${reason})`) }