OnClick 使用路由重定向到具有道具的组件

OnClick redirect to a component with props using route

我有一个清单, 当我点击一行时,我使用 onClickDetail 函数

从我的列表中检索了元素 ID

之后我想将用户重定向到传递此元素 ID 的新组件 我该如何处理?

App.js 路线:

 <HashRouter>
    <Provider store={store}>
      <Switch>
        <Route exact path="/login" name="Login Page" component={Login} />
        <Route exact path="/register" name="Register Page" component={Register} />
        <Route exact path="/404" name="Page 404" component={Page404} />
        <Route exact path="/500" name="Page 500" component={Page500} />
        <PersistGate loading={null} persistor={persistor}>
        <Route path="/" name="Home" component={DefaultLayout} />
        </PersistGate>
      </Switch>
      </Provider>
  </HashRouter>

我可以在哪里点击我的元素(this.props.currentElement 是一个 id):

        <td><i className="fa fa-edit fa-lg " style={{color: '#63c2de'}}
 onClick={this.handleClick.bind(this, this.props.currentElement)}></i></td>

我的点击函数:

    handleClick = (currentElement) => {
           console.log('list ref' , currentElemnt); // display my id ok
return (
        <Link to={"/listDetail/" + currentElement}>my list detail id : {currentElement}</Link>)
    }

我虽然加入了app.js

<Route path="/listDetail/:id" component={ListDetail}>

并添加到我的 onClickDetail 函数

<Link to={"/listDetail/" + id}>my list detail id : {id}</Link>

但它不起作用。除了 console.log

什么都没有发生

也许这不是最好的方法,所以我只是想知道如何处理 OnClick 以将我的用户重定向到传递道具的新组件。

故事情节应该是:

非常感谢

您可以使用 history 节点包中的推送方法,而不是使用 <Link/>

安装历史:npm install history

创建文件history.js: import createHistory from 'history/createBrowserHistory'; const history = createHistory(); export default history;

导入您想要更改的历史记录url。

您的 onClick 函数:(url) => history.push(url)

在您的路由器所在位置导入历史记录:

<Router history={history} />

这样试试:)

HomePage 组件中,因为它是从 <Route /> 渲染的,所以它应该接收 Router 属性,例如 matchhistory

因此,在您的 onClick 函数中,您只需要执行类似

的操作
function onClick(id) {
    this.props.history.push("/listDetail/" + id);
}