【问题标题】:ReactJS Link in a button component按钮组件中的 ReactJS 链接
【发布时间】:2019-02-05 20:03:54
【问题描述】:

我有:

import React, {Component} from 'react';
import {Link} from 'react-router-dom';

export default class NavItem extends Component {
    render() {
        return <Link to={'/test'}>
            <div className="navbar__item">
                <img src={'png/navigation/' + this.props.icon}/>
            </div>
        </Link>
    }
}

链接将通过道具传入的位置。但我不知道该怎么做,因为控制台告诉我它需要被包裹在路由器和路由中。

我怎样才能让它工作?


控制台给了我这个:

Warning: Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`.

我设法做到了:

render() {
        return <BrowserRouter>
            <Link to={this.props.url}>
                <div className="navbar__item">
                    <img src={'png/navigation/' + this.props.icon}/>
                </div>
            </Link>
        </BrowserRouter>
    }

【问题讨论】:

  • 您是否正在寻找使用按钮重定向的路由,而不是Linkhistory.push 在点击处理程序中可以完成同样的事情
  • @Andrew 我不确定,这只是一个按钮,可以将用户发送到我的应用程序中的另一个页面。链接是正确的方法吗?还是我应该只使用 标签?
  • Link 在 React 中比 Anchor 标签更常用。我没有看到您在代码中收到链接作为道具,也没有看到控制台日志在哪里。请分享相关信息
  • @HemadriDasari 我已经用控制台中的内容更新了我的问题。
  • 链接应该在 Routes 下,这意味着 NavItem 应该在 routes 下调用

标签: javascript reactjs


【解决方案1】:

我相信您只是想使用 history.push 作为 onclick 处理程序。它与Link 做同样的事情。

handleRouteChange = () => {
  history.push(this.props.routeName)
}

render() {
  return (
    <button onClick={this.handleRouteChange}>
      click
    </button>
  )
}

在您的应用初始化的某个时刻,您应该传入一个history 对象。导入需要history 的任何组件。它有一个push 方法。

export const history = createHashHistory()
<Router history={history}>
  <Routes />
</Router>

【讨论】:

  • 历史对象从何而来?
  • 已更新。它与您传递给 react 路由的 HOC 的对象相同
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-08
  • 2010-12-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
相关资源
最近更新 更多