GitHub iconTwitter icon

🌐 react

tips about react

Based on `react-router@v6`

function generatePaths(route: RouteObject, parentPath = '') {
  const { path, children } = route
  const fullPath = cleanDoubleSlashes(withoutTrailingSlash(`${parentPath}/${path ?? ''}`))

  let paths = new Set([fullPath])

  if (children) {
    for (const childRoute of children) {
      const childPaths = generatePaths(childRoute, fullPath)
      paths = new Set([...paths, ...childPaths])
    }
  }

  return paths
}

// Paths should be uniq
const paths = routes.flatMap(route => Array.from(generatePaths(route)))
<span>&nbsp;</span>

more functional

<span>
  {text === ' ' ? <>&nbsp;</> : text}
</span>

Here's what I've been using, similar to the other answer but without a dependency:

<Route
  exact
  path="/:id"
  render={props => (
    <Redirect to={`foo/${props.match.params.id}/bar`} />;
  )}
/>
  • 可替换HTMLElement为HTMLDivElement `React.HTMLAttributes<HTMLElement>`

在没有类型检查的`js`下相对容易,这里主要讨论的是`ts`

主要有两种方式。

使用 namespace

因为命名空间合并的规则,同名的`function``namespace`定义会合并

export function a() {}
export namespace a {
  export const b = b;
}

但是`function`的写法无法在使用`react.forwardref`之后和`namespace`一起使用

使用 as

in `a.tsx`

export const a = () => {};

in `index.tsx`

import { a as innera } from "./a";
import { b } from "./b";

type Innera = typeof innera;
interface a extends Innera {
  b: typeof b;
}
const a = innera as a;
a.b = b;
export default a;