React没有v-if、v-for怎么写都别扭

195 阅读1分钟

react对于逻辑的判断都是通过js来处理,好处呢就是会js就会react,不好呢页面如果逻辑判断多页面dom结构一堆 "?:",写个简单组件

  • For 控制循环
  • Switch/Match 控制多维度判断
  • Show 控制判断

For 控制循环

export default function For({ children, each }) {
  return each.map((item, index) => {
    return children(item, index);
  });
}

Match

import React from 'react';

export default function Match({ when, children }) {
  if (when !== true) {
    return null;
  }

  return <React.Fragment>{children}</React.Fragment>;
}

Show

export default function Show({ children, when }) {
  return when ? children : null;
}

Switch

import React from 'react';

export default function Switch({ fallback, children }) {
  if (!children) {
    if (fallback) return fallback;
    return null;
  }

  return (
    <React.Fragment>
      {React.Children.map(children, (child, index) => (
        <React.Fragment key={`switch-child-${index}`}>{child}</React.Fragment>
      ))}
    </React.Fragment>
  );
}

调用页面

import { useState } from "react";
import Show from "./components/Show";
import For from "./components/For";
import Switch from "./components/Switch";
import Match from "./components/Match";
import "./styles.css";

export default function App() {
  const [when, setWhen] = useState(true);
  const list = [1, 2, 3];
  return (
    <div className="App">
      <button onClick={() => setWhen((x) => !x)}>toggle</button>
      <Show when={when}>显示children</Show>
      <For each={list}>
        {(item, itemIndex) => (
          <div>
            {itemIndex} : {item}
          </div>
        )}
      </For>
      <Switch>
        <Match when={when}>显示true</Match>
        <Match when={!when}>显示false</Match>
      </Switch>
    </div>
  );
}

在线示例 codesandbox.io/s/react-if-…