【问题标题】:React Material UI Button component with hookrouter使用 hookrouter 反应 Material UI Button 组件
【发布时间】:2019-09-17 17:06:56
【问题描述】:

我正在尝试将类组件 React 应用程序迁移到带有钩子的功能组件。

在使用类组件时,我使用Link 组件将Button 组件传递给Button 组件,因为我使用的是react-router-dom 库。

但现在我正在尝试使用 Paratron/hookrouter 库进行路由,但在将 A 组件传递给 Button 时出现错误:

TypeError: props.href 未定义

我的代码现在看起来像这样:

import React, { Fragment } from 'react';
import { Grid, Button } from '@material-ui/core';
import { A } from 'hookrouter';
import './styles.css';

const Home = props => {
  return (
    <Fragment>
      <Grid container spacing={24} className="landing">
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="primary" 
            size="large"
            component={A}
            to="/login"
          >Login</Button>
        </Grid>
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="secondary" 
            size="large"
            component={A}
            to="/contact"
          >Contact us</Button>
        </Grid>
      </Grid>
    </Fragment>
  );
}

export default Home;

我猜这个A 组件不包含href 属性。不知道如何进行。任何 cmets 将不胜感激。

【问题讨论】:

    标签: reactjs material-ui hookrouter


    【解决方案1】:

    您需要提供 'href' 属性,而不是 'to' 属性。

    <Fragment>
      <Grid container spacing={24} className="landing">
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="primary" 
            size="large"
            component={A}
            href="/login" //href
          >Login</Button>
        </Grid>
        <Grid item xs={6}>
          <Button 
            variant="contained" 
            color="secondary" 
            size="large"
            component={A}
            href="/contact" //href
          >Contact us</Button>
        </Grid>
      </Grid>
    </Fragment>
    

    我还必须用类组件包装 A,因为 A 可能是函数组件,它们不能保存 ref(这是按钮组件 prop 所要求的)

    你可以参考这个工作CodeSandboxdemo

    【讨论】:

    • 我完全忘记了。 to 属性与 Link 组件相关。所以,这个hrefA 组件有关。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2019-05-24
    • 1970-01-01
    • 2020-02-16
    • 2020-08-12
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多