如何在 React-Router 中传递参数

用户7545438

我将 React 与 React Router 一起使用,并且我有 3 个链接与组件具有相同的路径。如何在点击组件时传递不同的参数?

const Example = props => {
  console.log("props", props);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
};

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path={"/example"} render={() => <Example />} />
      </Switch>
      <>
        <Link to={"/example"} params={{ name: "john" }}>
          <button>name</button>
        </Link>
        <Link to={"/example"} params={{ age: "27" }}>
          <button>age</button>
        </Link>
        <Link to={"/example"} params={{ surname: "Travolta" }}>
          <button>surname</button>
        </Link>
      </>
    </BrowserRouter>
  );
}

代码沙盒

苏莱曼萨

您可以使用Linkto属性,并使用 访问 Example 组件中的状态props.location.state

代码沙盒

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";
import "./styles.css";

const Example = props => {
  console.log("props", props.location.state);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
};

function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/example" component={Example} />
      </Switch>
      <>
        <Link to={{pathname:"/example", state: {name: "john"}}} >
          <button>name</button>
        </Link>
        <Link to={{pathname:"/example", state: {age: "27"}}} >
          <button>age</button>
        </Link>
        <Link to={{pathname:"/example", state: {surname: "Travolta"}}}  >
          <button>surname</button>
        </Link>
      </>
    </BrowserRouter>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在react-router-dom Link中传递参数?

React Router传递参数。如何?

如何在React Router v4中传递道具?

在React Router中传递可选参数

在React Router中传递其他参数

React Router-如何在路由匹配中约束参数?

如何在React Router中处理查询参数

如何在React Router中访问孩子?

将参数传递给React Router中的React元素

React Router无法传递参数

通过React Router传递参数

React-router-如何在React中的页面之间传递数据?

如何在react-testing-library中测试React Router路由参数?

如何在React + React-Router + Flux中处理查询参数

如何在使用中发送参数React Router Dom的历史?

如何在React-Router的组件中使用参数?

我如何在React Router上使用多个参数

处理通过组件中的react-router传递的参数

在React Router中,使用浏览器历史记录推送时如何传递路由参数?

如何在React Router dom v4中获取组件中的参数?

如何在React Native WebView中传递发布参数?

如何在React Native中的DateTimePicker上传递参数?

如何在获取请求中传递POST参数?-React Native

如何在React Native导航器中传递参数?

React JS:如何在查询参数中从 firebase 传递数组?

如何在Angular 4中使用Router参数传递和获取参数?

如何在React Router中链接到具有不同参数的当前页面?

如何在React Router dom(4.xx)中处理空URL参数

如何在 React Router 中获取多个字符串参数