【问题标题】:OnClick redirect to a component with props using routeOnClick 使用路由重定向到带有道具的组件
【发布时间】:2019-03-11 09:14:27
【问题描述】:

我有一个清单, 当我点击一行时,我使用 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 以将我的用户重定向到传递道具的新组件。

故事情节应该是:

  • 首页显示事物列表
  • 点击列表中的一个元素
  • 检索到元素 ID,用户被重定向到显示该特定元素的组件

非常感谢

【问题讨论】:

  • 您的onClickDetail 函数在代码中的什么位置?您能否也包括在内,所以所有相关代码都在您的问题中?
  • 错字? /listDeail/"/listDetail/:id"
  • 我更新了原来的帖子,@TomFinney 对不起,我改了名字,因为它对我的客户很重要

标签: reactjs routes onclick react-router-dom


【解决方案1】:

HomePage 组件中,由于它是从&lt;Route /&gt; 渲染的,它应该接收诸如matchhistory 之类的Router 属性。

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

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

【讨论】:

  • 非常感谢,我花了一点时间才明白我必须通过我的能力来传递历史,但多亏了你,它才有效!
【解决方案2】:

您可以使用来自history 节点包的推送方法,而不是使用&lt;Link/&gt;

安装历史:npm install history

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

导入您要更改网址的历史记录。

你的 onClick 函数:(url) =&gt; history.push(url);

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

&lt;Router history={history} /&gt;

试试这个方法:)

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 2015-11-06
    • 1970-01-01
    • 2020-02-13
    • 2021-03-31
    • 2018-12-25
    • 2020-02-13
    • 2020-07-08
    • 2021-02-04
    相关资源
    最近更新 更多