【问题标题】:material-ui fab href does not add baseurlmaterial-ui fab href 不添加 baseurl
【发布时间】:2020-11-26 13:39:57
【问题描述】:

在使用 material-ui 的 React 16 应用程序中。我有这个FAB

<Fab color = "primary" aria-label = "Add" className = {classes.fab}
     size = "small" href = "/technology/new">
    <AddIcon/>
</Fab>

应用程序配置为使用"metro" 作为基本 URL。所以所有路线和&lt;NavLink&gt; 都将metro 附加到链接中。例如 "/dashboard" 变为 "metro/dashboard"

问题是&lt;Fab&gt; 没有将metro 附加到链接。我该如何解决这个问题?

【问题讨论】:

  • Fab 默认在下面使用普通的 a 标签,因此它不会获得任何这些额外的逻辑。您可以通过将 FAB 使用的基本组件分配给 FABs 组件属性来替换它。您可以分配component={Link},然后使用to="/technology/new"
  • 如果你在codesandbox上重现这个会更容易赶上
  • @JacobSmit 我不明白。你的意思是 with Link is Link} from "@material-ui/core"; Fab 没有“to”属性。
  • @hgb123 我正在使用 ConnectedRouter 设置基本 url,如果我包含项目的设置方式,代码将太多。
  • 您可能想使用来自react-router-dom 的链接,抱歉,不是来自 MUI 的链接。

标签: reactjs material-ui floating-action-button


【解决方案1】:

您可以处理Fab 的点击事件并使用history.push() 以编程方式导航

const handleClick = () => {
  alert("already in here")
  // history.push('/technology/new')
}

return (
  <Fab color="primary" aria-label="add" onClick={handleClick}>
    <AddIcon />
  </Fab>
)

下面的演示代码和框

【讨论】:

    【解决方案2】:

    Material UI 不会自动与 React Router(或其他路由解决方案)连接。

    Material UI 确实提供了在使用外部组件实现功能的同时使用其组件样式,这将允许您使用 React Router DOM 的 Link 组件作为 Material UI 的 Fab 组件的基础。

    这是通过设置Fab组件的component prop来实现的(Material UI的大部分组件都有这个prop)。传入组件的属性应该可以直接在 Fab 组件上分配(参见示例)。

    import React, { Component } from 'react';
    import { render } from 'react-dom';
    import { Switch, BrowserRouter, Route, Redirect, Link } from 'react-router-dom';
    import { createBrowserHistory } from 'history';
    import Hello from './Hello';
    import './style.css';
    import { Fab } from '@material-ui/core';
    
    interface AppProps { }
    interface AppState { }
    
    const history = createBrowserHistory();
    
    class App extends Component<AppProps, AppState> {
      constructor(props) {
        super(props);
        this.state = {
          name: 'React'
        };
      }
    
      render() {
        return (
          <BrowserRouter 
            basename="test"
          >
            <Switch>
              <Route path="/b" render={() => <div>B</div>} />
              <Route path="/a" render={() => <div>A</div>} />
              <Redirect path="*" to="/a" />
            </Switch>
            <Fab component={Link} to='/a'>A</Fab>
            <Fab component={Link} to='/b'>B</Fab>
          </BrowserRouter>
        );
      }
    }
    
    render(<App />, document.getElementById('root'));
    

    可运行示例:https://stackblitz.com/edit/react-ts-cngowu?file=index.tsx

    【讨论】:

    • 完美,现在运行良好。感谢您的时间和精力。
    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2017-08-06
    • 2021-11-17
    • 2021-10-20
    • 2016-10-17
    相关资源
    最近更新 更多