【问题标题】:Pass prop through react router to component通过 react 路由器将 prop 传递给组件
【发布时间】:2020-03-02 17:59:15
【问题描述】:

我有一个组件,它是一个材料表。点击编辑按钮,我有这个功能:

//MaterialTable.js

...
const handleEdit = (e,Data) => {
    console.log(Data)
    return(<EditFunction  id={Data.id} />)
...

这应该运行EditFunction 组件,该组件接受props.id 并通过它的“id”从API 中提取数据并将其填充到自定义表单中以进行编辑然后再次保存。我在那里有console.log,以表明实际上调用了handleEdit,就是这样。所有匹配 'id' 的数据都打印在控制台中。

我不想直接调用该函数,而是想通过一个反应路由器来调用它。 //Routers.js

...
<Router>
    <Switch>
        <Route path = '/Data/Edit' render= {props=> <Edit/>}/>
    </Switch>
</Router>
...

我的目标是让 url 读取类似 localhost:3000/Data/Edit/id 的内容,其中 id 是该特定数据的 ID 号。

我不知道如何在 MaterialTable.js 文件中呈现链接。我知道这个语法在下面是错误的,但这是我能想到的唯一方法。 //MaterialTable.js

const handleEdit = (e,Data) => {
    console.log(Data)

    return(id = {Data.id} component={Link} to=Data/Edit/id)
...

【问题讨论】:

    标签: javascript reactjs material-ui react-router-dom material-table


    【解决方案1】:

    我想出了一个解决方案。下面列出了对文件的更改

    //Routers.js

    ...
    <Route path = '/Data/Edit/:id' component={Edit}/>
    ...
    

    //MaterialTable.js

    const handleEdit = (e,Data) => {
        const id = Data.id
        let idUrl = '/Data/Edit/' + id
        props.history.push(idUrl)
      }
    

    /Data/Edit/:id 中的 : 调用 Edit 函数并找到 prop 'id' 并将其值放入路由器中。在 MaterialTable.js 中,id 已定义,history.push 将路由更改为相应的 url。

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2023-03-27
      • 2020-10-27
      • 2019-07-21
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多