【问题标题】:How to ignore Material UI theme styling for component?如何忽略组件的 Material UI 主题样式?
【发布时间】:2019-12-30 16:13:00
【问题描述】:

我的按钮组件(也是一个材质 UI 组件)已经有了我想要的样式,但是当我用 Link 组件(一个 react-dom-router 组件)包围它时,它会覆盖我的按钮的样式。 如何忽略Link的默认样式?

<AppBar>
   <Toolbar>
      <Link to="/some-link">
          <Button>
              My Button
          </Button>
       </Link>
   </Toolbar>
</AppBar>

【问题讨论】:

  • 嗨@Akira Kotsugai,如果对您有帮助,您能否将其中一个答案标记为有效?

标签: reactjs react-router material-ui


【解决方案1】:

不要在Link 中嵌套一个按钮(这很奇怪,因为它们都是可点击的元素),只需使用带有onClick 处理程序的按钮,您可以在其中手动触发路由更改。

另见React-router: How to manually invoke Link?

【讨论】:

    【解决方案2】:

    这是材料 ui 网站上给出的示例。不过,您可能不需要路由器部分。

    https://material-ui.com/components/buttons/#ButtonRouter.js

    import React from 'react';
    import { MemoryRouter as Router } from 'react-router';
    import { Link } from 'react-router-dom';
    import Button from '@material-ui/core/Button';
    
    // The usage of React.forwardRef will no longer be required for react-router-dom v6.
    // see https://github.com/ReactTraining/react-router/issues/6056
    const AdapterLink = React.forwardRef((props, ref) => <Link innerRef={ref} {...props} />);
    
    const CollisionLink = React.forwardRef((props, ref) => (
      <Link innerRef={ref} to="/getting-started/installation/" {...props} />
    ));
    
    export default function ButtonRouter() {
      return (
        <Router>
          <Button color="primary" component={AdapterLink} to="/">
            Simple case
          </Button>
          <Button component={CollisionLink}>Avoids props collision</Button>
        </Router>
      );
    }
    

    【讨论】:

      【解决方案3】:

      在按钮 (&lt;button&gt;) 内嵌套链接 (&lt;a&gt;) 是无效的 HTML,反之亦然。我建议您删除 Button 或使用 react-router 并将 props.history.push("/some-link") 添加到您的 Button onClick 处理程序。像这样:

      <Button onClick={() => history.push("/some-link")}>My Button</Button>
      

      看看我做的this sandbox。如果有帮助,请告诉我。

      【讨论】:

        猜你喜欢
        • 2019-11-28
        • 2020-05-08
        • 2021-07-17
        • 2020-05-07
        • 1970-01-01
        • 2020-01-24
        • 1970-01-01
        • 2021-05-23
        • 2019-05-21
        相关资源
        最近更新 更多