我有一个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?


当前回答

import React from 'react';

import ListView from './ListView';
import TableView from './TableView';

function DataView({
    currView,
    data,
    onSelect,
    onChangeStatus,
    viewTodo,
    editTodo,
    deleteTodo,
}) {
    return (
        <div>
            {(function () {
                switch (currView) {
                    case 'table':
                        return (
                            <TableView
                                todos={data}
                                onSelect={onSelect}
                                onChangeStatus={onChangeStatus}
                                viewTodo={viewTodo}
                                editTodo={editTodo}
                                deleteTodo={deleteTodo}
                            />
                        );

                    case 'list':
                        return (
                            <ListView
                                todos={data}
                                onSelect={onSelect}
                                onChangeStatus={onChangeStatus}
                                viewTodo={viewTodo}
                                editTodo={editTodo}
                                deleteTodo={deleteTodo}
                            />
                        );

                    default:
                        break;
                }
            })()}
        </div>
    );
}

export default DataView;

其他回答

一种在渲染块中使用条件操作符表示一种开关的方法:

{(someVar === 1 &&
    <SomeContent/>)
|| (someVar === 2 &&
    <SomeOtherContent />)
|| (this.props.someProp === "something" &&
    <YetSomeOtherContent />)
|| (this.props.someProp === "foo" && this.props.someOtherProp === "bar" &&
    <OtherContentAgain />)
||
    <SomeDefaultContent />
}

应该确保条件严格返回布尔值。

  const [route, setRoute] = useState(INITIAL_ROUTE)

  return (
    <RouteContext.Provider value={{ route, setRoute }}>
      {(() => {
        switch (route) {
          case Route.Home:
            return <PopupHomePage />
          case Route.App:
            return <PopupAppPage />
          default:
            return null
        }
      })()}
    </RouteContext.Provider>

我在render()方法中做了这个:

  render() {
    const project = () => {
      switch(this.projectName) {

        case "one":   return <ComponentA />;
        case "two":   return <ComponentB />;
        case "three": return <ComponentC />;
        case "four":  return <ComponentD />;

        default:      return <h1>No project match</h1>
      }
    }

    return (
      <div>{ project() }</div>
    )
  }

我试图保持render()返回干净,所以我把我的逻辑放在一个'const'函数上面。这样我也可以缩进我的开关盒整齐。


function Notification({ text, status }) {
  return (
    <div>
      {(() => {
        switch (status) {
          case 'info':
            return <Info text={text} />;
          case 'warning':
            return <Warning text={text} />;
          case 'error':
            return <Error text={text} />;
          default:
            return null;
        }
      })()}
    </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})`) }