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


当前回答

我真的很喜欢https://stackoverflow.com/a/60313570/770134中的建议,所以我把它改成了Typescript

import React, { FunctionComponent } from 'react'
import { Optional } from "typescript-optional";
const { ofNullable } = Optional

interface SwitchProps {
  test: string
  defaultComponent: JSX.Element
}

export const Switch: FunctionComponent<SwitchProps> = (props) => {
  return ofNullable(props.children)
    .map((children) => {
      return ofNullable((children as JSX.Element[]).find((child) => child.props['value'] === props.test))
        .orElse(props.defaultComponent)
    })
    .orElseThrow(() => new Error('Children are required for a switch component'))
}

const Foo = ({ value = "foo" }) => <div>foo</div>;
const Bar = ({ value = "bar" }) => <div>bar</div>;
const value = "foo";
const SwitchExample = <Switch test={value} defaultComponent={<div />}>
  <Foo />
  <Bar />
</Switch>;

其他回答

改进了一点 马特·韦的回答。

export const Switch = ({ test, children }) => { const defaultResult = children.find((child) => child.props.default) || null; const result = children.find((child) => child.props.value === test); return result || defaultResult; }; export const Case = ({ children }) => children; const color = getColorFromTheMostComplexFnEver(); <Switch test={color}> <Case value="Green">Forest</Case> <Case value="Red">Blood</Case> <Case default>Predator</Case> </Switch> <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>
          { 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 />
    }
  }

我在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'函数上面。这样我也可以缩进我的开关盒整齐。

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;

我不太喜欢当前的任何答案,因为它们要么太啰嗦,要么需要您在代码中跳跃才能理解发生了什么。

我更喜欢用一个更以react组件为中心的方式来做这件事,通过创建一个<Switch/>。这个组件的任务是获取一个道具,并且只呈现子道具与该道具匹配的子元素。所以在下面的例子中,我在开关上创建了一个测试道具,并将其与子节点上的值道具进行比较,只渲染匹配的值道具。

例子:

const Switch = props => { const { test, children } = props // filter out only children with a matching prop return children.find(child => { return child.props.value === test }) } const Sample = props => { const someTest = true return ( <Switch test={someTest}> <div value={false}>Will display if someTest is false</div> <div value={true}>Will display if someTest is true</div> </Switch> ) } 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>

您可以根据自己的需要进行简单或复杂的切换。不要忘记对子节点及其值道具执行更健壮的检查。