javascript - 按钮组件中的 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>
}
解决方案
我相信您只是想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>
推荐阅读
- dataframe - 在 Julia DataFrames 中拆分字符串会出错
- google-apps-script - 新编辑器:如何保存版本
- php - 分享以查看页面标题
- python - 有没有办法将列转换为 30 分钟间隔的时间序列对象?
- node.js - Electron js - Spawn 子进程正在一台 Windows 机器上运行,但不在另一台机器上运行
- java - 带有 Hibernate 3.2.6/JPA 的 c3p0 连接池库 - 无法打开连接
- c# - Blazor 相当于 WPF 的 ItemsControl+DataTemplate
- java - 线程可以先通过安全发布获取对象,然后不安全地发布吗?
- html - HTML 页面像在根目录中一样解析相对链接
- pytorch - PyTorch - 内核在哪里启动?