React-router: Using <Link> as clickable data table row

点点圈 提交于 2020-04-09 04:57:14

问题


I'm new to using ReactJS and react-router. I want a clickable table row and something like the following setup:

<Link to=“#”>
<tr>
    <td>{this.props.whatever1}</td>
    <td>{this.props.whatever2}</td>
    <td>{this.props.whatever3}</td>
</tr>
</Link>

but I know you can't put <a> tags between the <tbody> and <tr> tags. How else can I accomplish this?

PS: I prefer not to use jQuery if possible.


回答1:


Why don't you just use onClick?

var ReactTable = React.createClass({
  handleClick: function(e) {
    this.router.transitionTo('index');
  },
  render: function() {
    return(
      <div>
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Age</th>
              <th>Full Detail</th>
            </tr>
          </thead>
            <tbody>
              <tr onClick={this.handleClick.bind(this)}>
                <td>{user.name}</td>
                <td>{user.age}</td>
                <td>{details}</td>
              </tr>
            </tbody>
        </table>
      </div>
    );
  }
});



回答2:


onClick works, but sometimes you need an actual <a> tag for various reasons:

  • Accessibility
  • Progressive enhancement (if script is throwing an error, links still work)
  • Ability to open a link in new tab
  • Ability to copy the link

Here's an example of a Td component that accepts to prop:

import React from 'react';
import { Link } from 'react-router-dom';

export default function Td({ children, to }) {
  // Conditionally wrapping content into a link
  const ContentTag = to ? Link : 'div';

  return (
    <td>
      <ContentTag to={to}>{children}</ContentTag>
    </td>
  );
}

Then use the component like this:

const users = this.props.users.map((user) =>
      <tr key={user.id}>
        <Td to={`/users/${user.id}/edit`}>{user.name}</Td>
        <Td to={`/users/${user.id}/edit`}>{user.email}</Td>
        <Td to={`/users/${user.id}/edit`}>{user.username}</Td>
      </tr>
    );

Yes, you'll have to pass to prop multiple times, but at the same you have more control over the clickable areas and you may have other interactive elements in the table, like checkboxes.



来源:https://stackoverflow.com/questions/35565012/react-router-using-link-as-clickable-data-table-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!