MST

星途 面试题库

面试题:Solid.js路由中如何处理嵌套路由及参数传递

在Solid.js路由系统搭建过程中,假设已有一个基础的路由结构,现在需要实现嵌套路由,并且父路由到子路由要传递一些参数,阐述实现的步骤及关键代码。
39.3万 热度难度
前端开发Solid.js

知识考点

AI 面试

面试题答案

一键面试

实现步骤

  1. 定义父路由组件:在父路由组件中,渲染子路由的占位符。
  2. 配置嵌套路由:在路由配置中,将子路由配置在父路由的children属性下。
  3. 传递参数:通过路由链接传递参数,或者在父组件向子组件传递参数。

关键代码

  1. 定义父路由组件
import { render } from "solid-js/web";
import { Router, Routes, Route } from "solid-router";

const ParentComponent = () => {
  const parentParam = "someValue";
  return (
    <div>
      <h1>Parent Component</h1>
      {/* 子路由占位符 */}
      <Routes>
        <Route path="child" component={ChildComponent} />
      </Routes>
    </div>
  );
};

const ChildComponent = (props) => {
  // 接收从父路由传递的参数
  const { parentParam } = props;
  return (
    <div>
      <h2>Child Component</h2>
      <p>Received param from parent: {parentParam}</p>
    </div>
  );
};

render(() => (
  <Router>
    <Routes>
      <Route path="/parent" component={ParentComponent} />
    </Routes>
  </Router>
), document.getElementById("app"));
  1. 另一种通过路由链接传递参数的方式
import { render } from "solid-js/web";
import { Router, Routes, Route, Link } from "solid-router";

const ParentComponent = () => {
  return (
    <div>
      <h1>Parent Component</h1>
      {/* 通过路由链接传递参数 */}
      <Link href="/parent/child?param=someValue">Go to Child</Link>
      <Routes>
        <Route path="child" component={ChildComponent} />
      </Routes>
    </div>
  );
};

const ChildComponent = () => {
  const params = new URLSearchParams(window.location.search);
  const paramValue = params.get('param');
  return (
    <div>
      <h2>Child Component</h2>
      <p>Received param from parent: {paramValue}</p>
    </div>
  );
};

render(() => (
  <Router>
    <Routes>
      <Route path="/parent" component={ParentComponent} />
    </Routes>
  </Router>
), document.getElementById("app"));