首页 > 解决方案 > 按钮组件中的 ReactJS 链接

问题描述

我有:

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>
    }

标签: javascriptreactjs

解决方案


我相信您只是想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>

推荐阅读