当用户单击下面的tableCell文本时,应该将他导航到http://localhost:3000/crayons/${rows.id}
我不确定如何编辑以下代码来执行以下操作

<TableBody>

{props.rows.slice(page).map(row => (
     <TableCell align="center">{row.crayon_color}</TableCell>

</TableBody>


我尝试了什么

<TableCell align="center" numeric component="a" href=`http://localhost:3000/crayons/${rows.id}`> {row.crayon_color}</TableCell>

最佳答案

EDIT更新了实时演示,以显示如何处理数组中的动态对象。

编辑2更新了实时演示和下面的代码,以反映如何将URL参数与动态对象一起使用。



我相信最简单的方法是使用<Link/>中的react-router-dom组件。

Live Demo Found Here



这是BrowserRouter的样子:

    <Switch>
      <Route exact path="/" component={Home} />
      <Route exact path="/crayons" component={Crayons} />
      <Route path="/crayons/:id" component={Crayons} />

      {/* MUST BE THE LAST ROUTE IN THIS LIST!!!! */}
      <Route component={FourZeroFour} />
    </Switch>




然后,在您的Crayons.js页面内部,您可以访问URL参数,在本例中为id,例如:props.match.params.id



演示Table代码:

// Build 'fake data' for table
const rows = Array.from(Array(10).keys()).map(item => {
  return {
    data: "Crayon",
    count: Math.floor(Math.random() * 100),
    id: item + 1
  }
})

export default function Home() {
  const classes = useStyles();

  return (
    <>
      <h1>Welcome to my app</h1>
      <Paper className={classes.root}>
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <TableCell>Data</TableCell>
              <TableCell>ID</TableCell>
              <TableCell>Count</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map(row => {
              return (
                <TableRow key={row.id}>
                  <TableCell component="th" scope="row">
                    {row.id
                      ? <Link to={`/crayons/${row.id}`}>{row.data}</Link>
                      : row.data}
                  </TableCell>
                  <TableCell>
                    {row.id}
                  </TableCell>
                  <TableCell>
                    {row.count}
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </Paper>
    </>
  )
}

关于javascript - 在React中使表格单元格可点击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57740279/

10-09 17:36
查看更多