【问题标题】:react-router-dom with material-uireact-router-dom 与 material-ui
【发布时间】:2019-07-19 19:28:40
【问题描述】:

我在我的 react (typescript) 应用程序中使用 material-ui 和 react-router-dom

我尝试使用以下提示/帮助,以便当用户单击按钮(或其他任何内容)时,他会被重定向到该路线。很基础的东西。当我单击该按钮时,URL 会在浏览器的 url 窗口中更新,但未加载正确的组件。我使用引导程序(和'react-router-bootstrap's NavigationLink)进行了这项工作,但现在我卡住了。任何提示如何使其正常工作

(我也使用 Mobx 作为状态处理程序),我对任何其他路由器也很满意,如果这能让我的生活更简单

https://material-ui.com/demos/buttons/How to make a Material UI react Button act as a react-router-dom Link?

请注意,如果我在 url 窗口中按 Enter 键,我会正确路由(到正确的组件)

【问题讨论】:

    标签: material-ui react-router-dom


    【解决方案1】:

    我正在使用这种方法为来自 material-ui 的Button 组件实现正确的 react-router-dom 链接。

    定义一个LinkComponent

    import * as React from 'react';
    import { Link } from 'react-router-dom';
    
    export const LinkComponent = (props: any) => {
      return <Link {...props} />;
    };
    

    那么你可以这样使用它:

    <Button
      variant={'outlined'}
      color={'primary'}
      component={LinkComponent}
      to={'/'}>
      HomePage
    </Button>
    

    如果您不想为此创建专用组件,可以将其用作 lambda 函数作为 &lt;Button&gt; 的组件道具。

    【讨论】:

    • 嗨,阿马尔!感谢您的回复。我在这里得到 2 个错误,我可能误解了你。我创建了 LinkComponent,但收到错误“(TS) 找不到名称 href”,因此我删除了“href ||”部分。在
    • ...但我在这里也找不到 to-attribute material-ui.com/api/button
    • ... 即使我硬编码
    • @Cowborg 抱歉找不到 href 错误,我更新了答案,请立即尝试。
    • 也试过了,没区别。我认为我的问题是如何使用 mobx 连接路由。我之前使用过 react-router-bootstrap,但是由于我现在不使用引导程序,所以我需要再次查看...我认为
    猜你喜欢
    • 2021-01-10
    • 1970-01-01
    • 2020-11-22
    • 2018-08-01
    • 2020-03-23
    • 2019-08-27
    • 2021-02-21
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多